0

I'm trying to write a function -- dict_reverse(inputDict) that returns a dictionary that has inputDict's keys and values swapped. (You can assume that no values are repeated in inputDict.)

I'm not really sure how to approach this problem as I am new to dictionaries. I understand their concept and how to use them, but I am stuck as for reversing them.

def dict_reverse(inputDict):
    '''dict_reverse(inputDict) -> dict
    returns dict with keys/values of inputDict swapped'''
    # add my code here

testDict = {'adam':80,'betty':60,'charles':50}
reversedDict = dict_reverse(testDict)
print(reversedDict)
# should output {80:'adam',60:'betty',50:'charles'} in some order

it should output {80:'adam',60:'betty',50:'charles'}

rm13
  • 67
  • 8

2 Answers2

1

Python 3

def dict_reverse(inputDict):
    '''dict_reverse(inputDict) -> dict
    returns dict with keys/values of inputDict swapped'''
    return dict((v,k) for k,v in inputDict.items())

testDict = {'adam':80,'betty':60,'charles':50}
reversedDict = dict_reverse(testDict)
print(reversedDict)

Output {80: 'adam', 60: 'betty', 50: 'charles'}

0

You can use a dict-comprehension and swap the k, v pairs:

def dict_reverse(inputDict):
    return {v: k for k, v in inputDict.items()}

testDict = {'adam': 80, 'betty': 60, 'charles': 50}
reversedDict = dict_reverse(testDict)
print(reversedDict)

Output:

{80: 'adam', 60: 'betty', 50: 'charles'}
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55