Merge List of Dictionaries in Python (2 Examples)

In this tutorial, you’ll learn how to merge a list of dictionaries in Python. Merging dictionaries involves combining multiple dictionaries into a single dictionary combining common key values. We’ll explore different methods to merge dictionaries in a list.

The table of contents is structured as follows:

Let’s dive into it!

Initializing a Sample List of Dictionaries

Firstly, let’s initialize a sample list of dictionaries that we’ll be working with throughout the tutorial:

# Initializing a list of dictionaries
list_of_dicts = [
    {'class_id': 1, 'students': ['John']},
    {'class_id': 2, 'students': ['Alice']},
    {'class_id': 3, 'students': ['Bob']},
    {'class_id': 3, 'students': ['Mike', 'Kyle']},
    {'class_id': 2, 'students': ['Diana', 'Olivia']}
]

This creates a list of dictionaries, where each dictionary represents an individual item with various key-value pairs. Note that there are duplicate class_id keys with different values.

Example 1: Using a for Loop

One way to merge the dictionaries in a list is using a for loop. Here’s an example:

# Merge using a for loop
merged_dict = {}
for dictionary in list_of_dicts:
    class_id = dictionary['class_id']
    students = dictionary['students']
    if class_id in merged_dict:
        merged_dict[class_id].extend(students)
    else:
        merged_dict[class_id] = students
 
# Print the merged dictionary
print(merged_dict)
# {1: ['John'], 2: ['Alice', 'Diana', 'Olivia'], 3: ['Bob', 'Mike', 'Kyle']}

In this example, we iterate over each dictionary in the list using a for loop. Within the loop, we extract the class_id and students values from each dictionary. We then check if class_id already exists in the merged_dict. If it does, we use extend() function to append the list of students for that class_id.

If the class_id is not present in the current merged dictionary merged_dict, we create a new key-value pair in the merged_dict with the current class_id as the key and the list of students students as the value.

Note that the final dictionary contains all the merged key-value pairs from all the dictionaries in the list list_of_dicts. As a result, the students for each class are combined into a single list in a dictionary.

Example 2: Using Dictionary Comprehension

Another method to merge dictionaries is using dictionary comprehension. Here’s an example:

# Merge using dictionary comprehension
merged_dict = {dictionary['class_id']: dictionary['students'] for dictionary in list_of_dicts}
 
# Print the merged dictionary
print(merged_dict)
# {1: ['John'], 2: ['Diana', 'Olivia'], 3: ['Mike', 'Kyle']}

In this example, we use dictionary comprehension to iterate over each dictionary in the list. We extract the class_id and students values from each dictionary and create a key-value pair in the merged_dict using class_id as the key and the list of students students as the value.

Using dictionary comprehension provides a concise and efficient way to merge dictionaries in a list. However, this method doesn’t merge the values with the duplicate keys, instead, it overwrites the previous entries.

This means if all keys are unique, it will produce the same merge_dict as the first example; otherwise, it will have a different result. Compare the results between Example 1 and Example 2.

Video, Further Resources & Summary

In this tutorial, we explored different methods to merge a list of dictionaries in Python. We saw that using a for loop or dictionary comprehension allows us to combine the dictionaries into a single merged dictionary.

Do you need more explanations on looping through a list of integers in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

The YouTube video will be added soon.

Furthermore, you could customize these methods based on your specific requirements or explore additional techniques and libraries available in Python to merge dictionaries. Also, you could have a look at some of the other tutorials on Statistics Globe:

 

Ömer Ekiz Python Programming & Informatics

This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top