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
- Take a dictionary as input.
- Create a function and pass a dictionary to it.
- Create an empty dictionary inside the function.
- Use for loop to iterate over keys and values of the input dictionary.
- 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.
- Return the dictionary.
- 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]}