---
# System prepended metadata

title: Refactoring Exercise

---

# 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.

## 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(dict):
   retVal = {}
   keys = list(dict.keys())
   for i in range(len(keys)):# for each key in input
       k = keys[i] # key
       v = 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
```python=
# Reverse the key-values in a dictionary and return a new dictionary
# Assume all values in dict are unique

import logging

def reverse_dictionary(dict):
   retVal = {}

   for k in dict.keys():
    if dict.get(k, None):
       retVal[dict.get(k)] = k
    else:
        log.warn('key exists. not doing anything.')
        raise Exception("Duplicate key exists")
   return retVal

####
# Class a
#   kdkdkd
#
class A

     """
         dkdfkddkd
     """
    def testDuplicateKeyValue():
        dict = {}
        dict['a'] = 1
        dict['b'] = 2
        try:
            reverse_diction(dict)
            fail("Expected duplicate key error")
        except (Exception e):
            pass
        
if __file__ == "main":
        
    
import testing

class UnitTest(Testing)