In this python dictionary program, we will invert a dictionary with non-unique hashable values.
Steps to solve the program
- Take a dictionary as input.
- From collections import defaultdict. (The Python defaultdict type behaves almost exactly like a regular Python dictionary, but if you try to access or modify a missing key, then defaultdict will automatically create the key and generate a default value for it)
- Take a variable and assign its value equal to defaultdict(list).
- Use for loop to iterate over keys and values of the input dictionary.
- Add the same values with the different keys as keys and their keys as values to that variable to that variable.
- Print the output.
from collections import defaultdict
D1 = {'alex':1,'bob':2,'martin':1,'robert':2}
obj = defaultdict(list)
for key, value in D1.items():
obj[value].append(key)
print(obj)
Output :
defaultdict(, {1: ['alex', 'martin'], 2: ['bob', 'robert']})