w3resource

Python: Grouping a sequence of key-value pairs into a dictionary of lists


46. Group Key-Value Pairs into Dictionary of Lists

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

Visual Presentation:

Python Dictionary: Grouping a sequence of key-value pairs into a dictionary of lists.

Sample Solution:

Python Code:

# Define a function 'grouping_dictionary' that groups a sequence of key-value pairs into a dictionary of lists.
def grouping_dictionary(l):
    # Create an empty dictionary 'result' to store the grouped data.
    result = {}
    for k, v in l:
        # Use 'setdefault' to append values 'v' to the list associated with key 'k'.
        result.setdefault(k, []).append(v)
    return result

# Create a list 'colors' containing key-value pairs (color, value).
colors = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

# Print a message indicating the start of the code section and the original list.
print("Original list:")
print(colors)

# Print a message indicating the intention to group the key-value pairs into a dictionary of lists.
print("\nGrouping a sequence of key-value pairs into a dictionary of lists:")

# Call the 'grouping_dictionary' function to group the key-value pairs and print the resulting dictionary.
print(grouping_dictionary(colors))

Sample Output:

Original list:
[('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

Grouping a sequence of key-value pairs into a dictionary of lists:
{'yellow': [1, 3], 'blue': [2, 4], 'red': [1]}

Flowchart:

Flowchart: Grouping a sequence of key-value pairs into a dictionary of lists.

For more Practice: Solve these Related Problems:

  • Write a Python program to group a list of key-value tuples into a dictionary where each key maps to a list of its associated values using collections.defaultdict.
  • Write a Python program to use dictionary comprehension to form a dictionary of lists from a sequence of tuples.
  • Write a Python program to iterate over a list of pairs and build a grouped dictionary, appending values for duplicate keys.
  • Write a Python function to convert a list of key-value pairs into a dictionary of lists, ensuring order is preserved.

Go to:


Previous: Write a Python program to check all values are same in a dictionary.
Next: Write a Python program to split a given dictionary of lists into list of dictionaries.

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.