How to merge multiple Python dictionaries?

PythonServer Side ProgrammingProgramming

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
Published on 29-Dec-2017 13:56:07
Advertisements