For dictionaries and x, their shallowly-merged dictionary y takes values from z, replacing those from y.x
In Python 3.9.0 or greater (released 17 October 2020, , discussed here):PEP-584
z = x | y
In Python 3.5 or greater:
z = {**x, **y}
In Python 2, (or 3.4 or lower) write a function:
def merge_two_dicts(x, y):
z = x.copy() # start with keys and values of x
z.update(y) # modifies z with keys and values of y
return z
and now:
z = merge_two_dicts(x, y)
Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
The desired result is to get a new dictionary () with the values merged, and the second dictionary's values overwriting those from the first.z
>>> z
{'a': 1, 'b': 3, 'c': 4}
A new syntax for this, proposed in PEP 448 and available as of Python 3.5, is
z = {**x, **y}
And it is indeed a single expression.
Note that we can merge in with literal notation as well:
z = {**x, 'foo': 1, 'bar': 2, **y}
and now:
>>> z
{'a': 1, 'b': 3, 'foo': 1, 'bar': 2, 'c': 4}
It is now showing as implemented in the release schedule for 3.5, PEP 478, and it has now made its way into the What's New in Python 3.5 document.
However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:
z = x.copy()
z.update(y) # which returns None since it mutates z
In both approaches, will come second and its values will replace y's values, thus x will point to b in our final result.3
If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a single expression, the most performant while the correct approach is to put it in a function:
def merge_two_dicts(x, y):
"""Given two dictionaries, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z
and then you have a single expression:
z = merge_two_dicts(x, y)
You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number:
def merge_dicts(*dict_args):
"""
Given any number of dictionaries, shallow copy and merge into a new dict,
precedence goes to key-value pairs in latter dictionaries.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries to a:g
z = merge_dicts(a, b, c, d, e, f, g)
and key-value pairs in will take precedence over dictionaries g to a, and so on.f
Don't use what you see in the formerly accepted answer:
z = dict(x.items() + y.items())
In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. In Python 3, this will fail because you're adding two objects together, not two lists -dict_items
>>> c = dict(a.items() + b.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
and you would have to explicitly create them as lists, e.g. . This is a waste of resources and computation power.z = dict(list(x.items()) + list(y.items()))
Similarly, taking the union of in Python 3 (items() in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, since sets are semantically unordered, the behavior is undefined in regards to precedence. So don't do this:viewitems()
>>> c = dict(a.items() | b.items())
This example demonstrates what happens when values are unhashable:
>>> x = {'a': []}
>>> y = {'b': []}
>>> dict(x.items() | y.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
Here's an example where should have precedence, but instead the value from y is retained due to the arbitrary order of sets:x
>>> x = {'a': 2}
>>> y = {'a': 1}
>>> dict(x.items() | y.items())
{'a': 2}
Another hack you should not use:
z = dict(x, **y)
This uses the constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it's difficult to read, it's not the intended usage, and so it is not Pythonic.dict
Here's an example of the usage being remediated in django.
Dictionaries are intended to take hashable keys (e.g. s or tuples), but this method fails in Python 3 when keys are not strings.frozenset
>>> c = dict(a, **b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: keyword arguments must be strings
From the mailing list, Guido van Rossum, the creator of the language, wrote:
I am fine with declaring dict({}, **{1:3}) illegal, since after all it is abuse of the ** mechanism.
and
Apparently dict(x, **y) is going around as "cool hack" for "call x.update(y) and return x". Personally, I find it more despicable than cool.
It is my understanding (as well as the understanding of the creator of the language) that the intended usage for is for creating dictionaries for readability purposes, e.g.:dict(**y)
dict(a=1, b=10, c=11)
instead of
{'a': 1, 'b': 10, 'c': 11}
Despite what Guido says,
is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact, ** was designed precisely to pass dictionaries as keywords.dict(x, **y)
Again, it doesn't work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. broke this consistency in Python 2:dict
>>> foo(**{('a', 'b'): None})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() keywords must be strings
>>> dict(**{('a', 'b'): None})
{('a', 'b'): None}
This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.
I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.
More comments:
is still the most readable solution for Python 2. Readability counts.dict(x.items() + y.items())
My response: actually seems much clearer to me, if we're actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.merge_two_dicts(x, y)
does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged [...] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word "merging" these answers describe "updating one dict with another", and not merging.{**x, **y}
Yes. I must refer you back to the question, which is asking for a shallow merge of two dictionaries, with the first's values being overwritten by the second's - in a single expression.
Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them:
from copy import deepcopy
def dict_of_dicts_merge(x, y):
z = {}
overlapping_keys = x.keys() & y.keys()
for key in overlapping_keys:
z[key] = dict_of_dicts_merge(x[key], y[key])
for key in x.keys() - overlapping_keys:
z[key] = deepcopy(x[key])
for key in y.keys() - overlapping_keys:
z[key] = deepcopy(y[key])
return z
Usage:
>>> x = {'a':{1:{}}, 'b': {2:{}}}
>>> y = {'b':{10:{}}, 'c': {11:{}}}
>>> dict_of_dicts_merge(x, y)
{'b': {2: {}, 10: {}}, 'a': {1: {}}, 'c': {11: {}}}
Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at my answer to the canonical question on a "Dictionaries of dictionaries merge".
These approaches are less performant, but they will provide correct behavior.
They will be much less performant than and copy or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they do respect the order of precedence (latter dictionaries have precedence)update
You can also chain the dictionaries manually inside a dict comprehension:
{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7
or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):
dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2
will chain the iterators over the key-value pairs in the correct order:itertools.chain
from itertools import chain
z = dict(chain(x.items(), y.items())) # iteritems in Python 2
I'm only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.)
from timeit import repeat
from itertools import chain
x = dict.fromkeys('abcdefg')
y = dict.fromkeys('efghijk')
def merge_two_dicts(x, y):
z = x.copy()
z.update(y)
return z
min(repeat(lambda: {**x, **y}))
min(repeat(lambda: merge_two_dicts(x, y)))
min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
min(repeat(lambda: dict(chain(x.items(), y.items()))))
min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
In Python 3.8.1, NixOS:
>>> min(repeat(lambda: {**x, **y}))
1.0804965235292912
>>> min(repeat(lambda: merge_two_dicts(x, y)))
1.636518670246005
>>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
3.1779992282390594
>>> min(repeat(lambda: dict(chain(x.items(), y.items()))))
2.740647904574871
>>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
4.266070580109954
$ uname -a
Linux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux
If you're interested in creating a new dict without using intermediary storage: (this is faster, and in my opinion, cleaner than using )dict.items()
dic2 = dict(dic0, **dic1)
Or if you're happy to use one of the existing dicts:
dic0.update(dic1)
Since you're using Python 3, one possible approach would be:
>>> A = {(3,'x'):-2, (6,'y'):3, (8, 'b'):9}
>>> B = {(3,'y'):4, (6,'y'):6}
>>> {k: A.get(k,0) + B.get(k,0) for k in A.keys() | B.keys()}
{(8, 'b'): 9, (3, 'x'): -2, (6, 'y'): 9, (3, 'y'): 4}
In Python 3, returns a .keys() object, and we can use the dict_keys operator to take the union of the two. (That's why | won't work.)A.keys() + B.keys()
(I'd probably use a myself, FWIW.)Counter
this is a one-liner that would do just that:
dict1 = {'a': 5, 'b': 7}
dict2 = {'a': 3, 'c': 1}
result = {key: dict1.get(key, 0) + dict2.get(key, 0)
for key in set(dict1) | set(dict2)}
# {'c': 1, 'b': 7, 'a': 8}
note that is the set of the keys of both your dictionaries. and set(dict1) | set(dict2) returns dict1.get(key, 0) if the key exists, dict1[key] otherwise.0
this works on a more recent python version:
{k: dict1.get(k, 0) + dict2.get(k, 0) for k in dict1.keys() | dict2.keys()}
I would do it like this:
>>> fst = {'A': 5, 'B': 6, 'C': 8}
>>> snd = {'A': 4, 'B': 9, 'E': 2}
>>> out = {k: fst[k] + snd[k] for k in fst.keys() & snd.keys()}
>>> out.update({k: fst[k] if k in fst else snd[k] for k in fst.keys() ^ snd.keys()})
>>> out
{'A': 9, 'B': 15, 'C': 8, 'E': 2}
You can easily add two dictionaries by using Counter class of collections library for ex:
from collections import Counter
a = {'a':10,'b':11,'c':20}
b = {'a':1,'b':1,'c':1}
a = Counter(a)
b = Counter(b)
c = dict(a + b)
print c
OUTPUT
{'c': 21, 'b': 12, 'a': 11}
You could use .Object.assign
var a = { fruit: "apple" },
b = { vegetable: "carrot" },
food = Object.assign({}, a, b);
console.log(food);
For browser without supporting , you could iterate the properties and assign the values manually.Object.assign
var a = { fruit: "apple" },
b = { vegetable: "carrot" },
food = [a, b].reduce(function (r, o) {
Object.keys(o).forEach(function (k) { r[k] = o[k]; });
return r;
}, {});
console.log(food);
This is a generic version. This can be used to create a dictionary with values as a list, even if the key is present in only one of them.
dic1 = {'A': 25, 'B': 41, 'C': 32}
dic2 = {'A': 21, 'B': 12, 'C': 62}
result = {}
for key in (dic1.keys() | dic2.keys()):
if key in dic1: result.setdefault(key, []).append(dic1[key])
if key in dic2: result.setdefault(key, []).append(dic2[key])
print(result)
Output
{'A': [25, 21], 'C': [32, 62], 'B': [41, 12]}
If you are using Python 2, for loop has to be changed like this:
for key in (dic1.viewkeys() | dic2.keys()):
pd.DataFrame({'monkeydict':pd.Series(monkeydict),'pigdict':pd.Series(pigdict)})
Out[879]:
monkeydict pigdict
16:41 NaN 3.0
16:43 1.0 NaN
16:44 1.0 2.0
16:49 3.0 NaN
16:51 NaN 3.0
Or (Notice here, you need to rename your columns after create the data frame)
pd.DataFrame([monkeydict,pigdict]).T
Out[887]:
0 1
16:41 NaN 3.0
16:43 1.0 NaN
16:44 1.0 2.0
16:49 3.0 NaN
16:51 NaN 3.0