Python (Scripting) - Merge Dictionaries

by
Jeremy Canfield |
Updated: October 21 2024
| Python (Scripting) articles
In this example, the keys and values in dict1 and dict2 are merged. If dict1 and dict2 contain an identical key, such as "foo" the final dictionary will contain the key/value pair from dict2.
#!/usr/bin/python3
dict1 = {
"foo": "Hello",
"bar": "World"
}
dict2 = {
"foo": "Goodbye",
"baz": "World"
}
merged_dict = {}
for item in dict1, dict2:
for key, value in item.items():
merged_dict[key] = value
print(f"merged_dict = {merged_dict}")
In this example, the merged dict would be this.
{'foo': 'Goodbye', 'bar': 'World', 'baz': 'World'}
In this example, there are two lists that contain a dictionary. The final list will contain the dictionaries from list1 and list2.
#!/usr/bin/python3
list1 = [
{
"name": "John Doe",
"department": "IT"
},
{
"name": "Jane Doe",
"department": "Sales"
}
]
list2 = [
{
"name": "John Doe",
"department": "IT"
},
{
"name": "Jane Doe",
"department": "Human Resources"
}
]
merged_list = []
for x in list1, list2:
for item in x:
merged_list.append(item)
print(f"merged_list = {merged_list}")
In this example, the merged list would be this.
[
{'name': 'John Doe', 'department': 'IT'},
{'name': 'Jane Doe', 'department': 'Sales'},
{'name': 'John Doe', 'department': 'IT'},
{'name': 'Jane Doe', 'department': 'Human Resources'}
]
You could do something like this to prevent identical keys from being appended to the final list.
#!/usr/bin/python3
list1 = [
{
"name": "John Doe",
"department": "IT"
},
{
"name": "Jane Doe",
"department": "Sales"
}
]
list2 = [
{
"name": "John Doe",
"department": "IT"
},
{
"name": "Jane Doe",
"department": "Human Resources"
}
]
merged_list = []
for x in list1, list2:
for item in x:
if not any(item['name'] in y['name'] for y in merged_list):
print(f"{item['name']} is NOT in merged_list - appending {item} to merged_list")
merged_list.append(item)
print(f"merged_list = {merged_list}")
Did you find this article helpful?
If so, consider buying me a coffee over at