Create a dictionary grouping a sequence of key-value pairs.

In this python dictionary program, we will create a dictionary grouping a sequence of key-value pairs into a dictionary of lists.

Steps to solve the program
  1. Take a dictionary as input.
  2. Create a function and pass a dictionary to it.
  3. Create an empty dictionary inside the function.
  4. Use for loop to iterate over keys and values of the input dictionary.
  5. Add a grouping of a sequence of key-value pairs using setdefault(k, []).append(v), where k is the key and v in the value for that key.
  6. Return the dictionary.
  7. Now pass the input dictionary to the function to print the output.
				
					D1 = [('virat',50), ('rohit',40), ('virat',30), ('rohit',10)]

def grouping_dictionary(l):
    result = {}
    for k, v in l:
         result.setdefault(k, []).append(v)
    return result
print(grouping_dictionary(D1))
				
			

Output :

				
					{'virat': [50, 30], 'rohit': [40, 10]}
				
			

check all values are the same in a dictionary.

split a given dictionary of lists into list of dictionaries.

Leave a Comment