Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I merge dictionaries together in Python?

d3 = dict(d1, **d2) 

I understand that this merges the dictionary. But, is it unique? What if d1 has the same key as d2 but different value? I would like d1 and d2 to be merged, but d1 has priority if there is duplicate key.

like image 820
TIMEX Avatar asked May 09 '10 20:05

TIMEX


People also ask

Which function helps merge two dictionaries in Python?

Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.

Which function helps merge dictionary?

Dictionary is also iterable, so we can use itertools. chain() to merge two dictionaries. The return type will be itertools.

How do I concatenate a dictionary list?

To merge multiple dictionaries, the most Pythonic way is to use dictionary comprehension {k:v for x in l for k,v in x. items()} to first iterate over all dictionaries in the list l and then iterate over all (key, value) pairs in each dictionary.


2 Answers

You can use the .update() method if you don't need the original d2 any more:

Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.

E.g.:

>>> d1 = {'a': 1, 'b': 2}  >>> d2 = {'b': 1, 'c': 3} >>> d2.update(d1) >>> d2 {'a': 1, 'c': 3, 'b': 2} 

Update:

Of course you can copy the dictionary first in order to create a new merged one. This might or might not be necessary. In case you have compound objects (objects that contain other objects, like lists or class instances) in your dictionary, copy.deepcopy should also be considered.

like image 172
Felix Kling Avatar answered Sep 23 '22 06:09

Felix Kling


In Python2,

d1={'a':1,'b':2} d2={'a':10,'c':3} 

d1 overrides d2:

dict(d2,**d1) # {'a': 1, 'c': 3, 'b': 2} 

d2 overrides d1:

dict(d1,**d2) # {'a': 10, 'c': 3, 'b': 2} 

This behavior is not just a fluke of implementation; it is guaranteed in the documentation:

If a key is specified both in the positional argument and as a keyword argument, the value associated with the keyword is retained in the dictionary.

like image 37
unutbu Avatar answered Sep 24 '22 06:09

unutbu