[891] Combine multiple dictionaries in Python
To combine multiple dictionaries in Python, you can use any of the methods mentioned earlier for combining two dictionaries. You can repeatedly apply these methods to merge multiple dictionaries into one. Here's how you can do it:
Using the update()
Method (for Combining Multiple Dictionaries):
You can use a loop to iteratively update a target dictionary with the key-value pairs from multiple source dictionaries:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'d': 5, 'e': 6}
merged_dict = dict1.copy() # Make a copy of the first dictionary
# Update the copy with the key-value pairs from the other dictionaries
for d in [dict2, dict3]:
merged_dict.update(d)
After this operation, merged_dict
will be {'a': 1, 'b': 3, 'c': 4, 'd': 5, 'e': 6}
.