Computer >> Computer tutorials >  >> Programming >> Python

How to merge multiple Python dictionaries?


First, put all dictionary objects in a list object.

Initialize a dictionary object to empty directory. This is intended to contain merged directory

Example

Update it with each directory item from the list

>>> d=[{'a':1, 'b':2, 'c':3}, {'a':1, 'd':2, 'c':'foo'}, {'e':57,'c':3}]
>>> d
[{'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'd': 2, 'c': 'foo'}, {'e': 57, 'c': 3}]
>>> merged={}
>>> for x in d:
    merged.update(x)

>>> merged
{'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 57}