---
# System prepended metadata

title: Python Refactoring Exercise

---

# Python Refactoring Exercise

In a project you contribute to, there is an open issue asking for a feature to invert the key, value pairs of a python dictionary.  Some examples:

```
{} -> {}
{'a': '1'} -> {'1': 'a'}
{'a': '1', 'b': '2'} -> {'1': 'a', '2': 'b'}
```

You receive the following code in a pull request to close the issue.  It is functional, but is failing checks for style, PEP8 formatting, and isn't very 'pythonic'.  The developer has clearly missed the suggested best practices for contributions.

- Refactor the code to address as many issues as you can identify.
- As you work, describe the process you normally follow for making changes and why/how the changes improve the code.
- Feel free to change any aspect of the code; as a new feature it currently has no dependencies.
- You can assume you are working with Python 3.8+

## Pull request
```python=
# Reverse the key-values in a dictionary and return a new dictionary
# Assume all values in dict are unique

def reverse_dictionary(input_dict):
   retVal = {}
   keys = list(input_dict.keys())            
   for i in range(len(keys)):# for each key in input
       k = keys[i] # key
       v = input_dict[k] # value
       if (v not in retVal):
           retVal[v] = k
       else:
           print('key exists. not doing anything.')
           pass
   return retVal
```

## Start revising this copy

#-read through this 
#-annotations 
#-doc string 
#make sure it does what it purports to do 
#redundancy reduction 
#pep8 


```python=
# Reverse the key-values in a dictionary and return a new dictionary
# Assume all values in dict are unique

def reverse_dictionary(input_dict: dict) -> dict:
    """
    Reverse the key-values in a dictionary and return a new dictionary
    
    Arguments:
        input_dict:
        
    Exception: 
        keyerror: 
    """
    
   reversed_dictionary = {}
   keys = list(input_dict.keys()) 
   values = list(input_dict.values())
   #
   for key in input_dict:
       reversed_dictionary[input_dict[key]] = key
   #

   for i in range(len(input_dict)):
       key   = keys[i]
       
       value = values[i]
       reversed_dictionary[value] = key  
        
   return reversed_dictionary
```

def test_reverse_dictionary():
    #-toy example where two values are the same 
    input_dict = {'a':'b','c':'b'}
    
    test = reverse_dictionary(input_dict)
    
    assert test
    