Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Merging two list of dictionaries in Python
When working with Python data structures, you may need to combine multiple lists of dictionaries into a single list. This operation preserves all dictionaries from both lists while maintaining their original order and structure.
In this article, we'll explore two effective methods for merging lists of dictionaries: the + operator and the extend() method. Both approaches create a unified list containing all dictionaries from the input lists.
Using the '+' Operator
The + operator creates a new list by concatenating two existing lists without modifying the original lists ?
# Define two lists of dictionaries
list1 = [{'name': 'Sarita', 'age': 25}, {'name': 'Alice', 'age': 30}]
list2 = [{'name': 'Bob', 'age': 35}, {'name': 'Sara', 'age': 28}]
# Merge using + operator
merged_list = list1 + list2
print("Original list1:", list1)
print("Original list2:", list2)
print("Merged list:", merged_list)
Original list1: [{'name': 'Sarita', 'age': 25}, {'name': 'Alice', 'age': 30}]
Original list2: [{'name': 'Bob', 'age': 35}, {'name': 'Sara', 'age': 28}]
Merged list: [{'name': 'Sarita', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 35}, {'name': 'Sara', 'age': 28}]
Using the extend() Method
The extend() method modifies the first list by adding all elements from the second list. To preserve the original list, create a copy first ?
# Define two lists of dictionaries
list1 = [{'name': 'Sarita', 'salary': 55000}, {'name': 'Alice', 'salary': 30000}]
list2 = [{'name': 'Bob', 'salary': 35000}, {'name': 'Sara', 'salary': 28000}]
# Create a copy to preserve the original list
merged_list = list1.copy()
merged_list.extend(list2)
print("Original list1:", list1)
print("Original list2:", list2)
print("Merged list:", merged_list)
Original list1: [{'name': 'Sarita', 'salary': 55000}, {'name': 'Alice', 'salary': 30000}]
Original list2: [{'name': 'Bob', 'salary': 35000}, {'name': 'Sara', 'salary': 28000}]
Merged list: [{'name': 'Sarita', 'salary': 55000}, {'name': 'Alice', 'salary': 30000}, {'name': 'Bob', 'salary': 35000}, {'name': 'Sara', 'salary': 28000}]
Comparison
| Method | Modifies Original? | Memory Usage | Best For |
|---|---|---|---|
+ operator |
No | Creates new list | Preserving original data |
extend() |
Yes (first list) | Modifies existing list | Memory efficiency |
Conclusion
Both the + operator and extend() method effectively merge lists of dictionaries. Use the + operator when you need to preserve original lists, and extend() for memory-efficient operations where modifying the first list is acceptable.
