views:

533

answers:

3
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.

+6  A: 

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 objects in your dictionary, copy.deepcopy should also be considered.

Felix Kling
With this case d1 elements should correctly get priority if conflicting keys are found
Trey
In case you still need it, just make a copy.d3 = d2.copy()d3.update(d1)but I would like to see d1 + d2 being added to the language.
stach
d1 + d2 is problematic because one dictionary has to have priority during conflicts, and it's not particularly obvious which one.
rjh
d1 + d2 will only ever be implemented if Python gains a multimap, otherwise the ambiguity to the user is too confusing for the 8 byte typing gain.
Nick Bastin
+6  A: 

.

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.

unutbu
Your examples will fail (producing a TypeError) in Python 3.2, and in current versions of Jython, PyPy and IronPython: for those versions of Python, when passing a dict with the `**` notation, all the keys of that dict should be strings. See the python-dev thread starting at http://mail.python.org/pipermail/python-dev/2010-April/099427.html for more.
Mark Dickinson
@Mark: Thanks for the heads up. I've edited the code to make it compatible with non-CPython implementations.
unutbu
A: 

If you want d1 to have priority in the conflicts, do:

d3 = d2.copy()
d3.update(d1)

Otherwise, reverse d2 and d1.

ΤΖΩΤΖΙΟΥ
This is not correct, update returns None, not self.
Joe
@Joe: thanks for the correction.
ΤΖΩΤΖΙΟΥ