In this python dictionary program, we will group the same items into a dictionary values.
Stpes to solve the program
- Take a list of the same items as input.
- From collections import defaultdict.
- Create a variable and assign its value equal to defaultdict(list).
- Use for loop to iterate over items in the list.
- Add the item as a key and group the same items from the list as its value to the variable using append().
- Print the output.
from collections import defaultdict
list1 = [1,3,4,4,2,5,3,1,5,5,2]
print("The original list : ",list1)
dict1 = defaultdict(list)
for val in list1:
dict1[val].append(val)
print("Similar grouped dictionary :" ,dict1)
Output :
The original list : [1, 3, 4, 4, 2, 5, 3, 1, 5, 5, 2]
Similar grouped dictionary : defaultdict(, {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5, 5]})