How to merge multiple Python dictionaries?

ProgrammingPythonServer Side Programming

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}
raja
Updated on 25-Aug-2022 12:01:32

Advertisements