Python program to invert a dictionary with non-unique hashable values.

In this python dictionary program, we will invert a dictionary with non-unique hashable values.

Steps to solve the program
  1. Take a dictionary as input.
  2. 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)
  3. Take a variable and assign its value equal to defaultdict(list).
  4. Use for loop to iterate over keys and values of the input dictionary.
  5. Add the same values with the different keys as keys and their keys as values to that variable to that variable.
  6. 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(<class 'list'>, {1: ['alex', 'martin'], 2: ['bob', 'robert']})
				
			

rename key of a dictionary

Sort Dictionary by values summation

Leave a Comment