Group the same items into a dictionary values list.

In this python dictionary program, we will group the same items into a dictionary values.

Stpes to solve the program
  1. Take a list of the same items as input.
  2. From collections import defaultdict.
  3. Create a variable and assign its value equal to defaultdict(list).
  4. Use for loop to iterate over items in the list.
  5. Add the item as a key and group the same items from the list as its value to the variable using append().
  6. 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(<class 'list'>, {1: [1, 1], 3: [3, 3], 4: [4, 4], 2: [2, 2], 5: [5, 5, 5]})
				
			

find maximum and minimum values in a dictionary.

replace words in a string using a dictionary.

Leave a Comment