Nov-19-2020, 04:58 PM
This is the dictionary you are trying to make:
Lets try building the dictionary step by step:
This is a potential problem with inverting a dictionary. A dictionary does not care if the values are unique, only the keys. When you swap keys and values the dictionary will happily overwrite any duplicate values. You could make this a key error.
Output:{3:'I', 3:'love', '2':'self.py!'}
Lets see what happens if we try to create the dictionary from a literal.inverse_dict = {3:'I', 3:'love', 2:'self.py!'} print(inverse_dict)
Output:{3: 'love', '2': 'self.py!'}
Hmmm, same problem.Lets try building the dictionary step by step:
inverse_dict = {} inverse_dict[3] = 'I' inverse_dict[3] = 'love' inverse_dict[2] = 'self.py!' print(inverse_dict)
Output:{3: 'love', '2': 'self.py!'}
Hopefully this last example makes it clear why 'love' replaces 'I' when you SET inverse_dict[3] = 'love'. The keys in a dictionary are unique. When you set the key:value in a dictionary it sets the value associated with the key. If the key does not exist the key is added.This is a potential problem with inverting a dictionary. A dictionary does not care if the values are unique, only the keys. When you swap keys and values the dictionary will happily overwrite any duplicate values. You could make this a key error.
course_dict = {'I': 3, 'love': 3, 'self.py!': 2} def inverse_dict(my_dict): new_dict = {} for key, value in my_dict.items(): if value in new_dict: raise KeyError(f'Key {value} already exists') new_dict[value] = key return new_dict print(inverse_dict(course_dict))
Output:Traceback (most recent call last):
File "...", line 14, in <module>
print(inverse_dict(course_dict))
File "...", line 8, in inverse_dict
raise KeyError(f'Key {value} already exists')
KeyError: 'Key 3 already exists'