Q:

Write a Python program to create a dictionary grouping a sequence of key-value pairs into a dictionary of lists. Use collections module.

0

Write a Python program to create a dictionary grouping a sequence of key-value pairs into a dictionary of lists. Use collections module.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

from collections import defaultdict
def grouping_dictionary(l):
    d = defaultdict(list)
    for k, v in l:
        d[k].append(v)
    return d
colors = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
print("Original list:")
print(colors)
print("\nGrouping a sequence of key-value pairs into a dictionary of lists:")
print(grouping_dictionary(colors))

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now