<p>I want to merge two dictionaries into a new dictionary.</p>
<pre><code>x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)

&gt;&gt;&gt; z
{'a': 1, 'b': 3, 'c': 4}
</code></pre>
<p>Whenever a key <code>k</code> is present in both dictionaries, only the value <code>y[k]</code> should be kept.</p>

[{'answer_id': 38989, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 7, 'selected': False, 'text': "<pre><code>x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\nz = dict(x.items() + y.items())\nprint z\n</code></pre>\n\n<p>For items with keys in both dictionaries ('b'), you can control which one ends up in the output by putting that one last.</p>\n"}, {'answer_id': 38990, 'author': 'Thomas Vander Stichele', 'author_id': 2900, 'author_profile': 'https://Stackoverflow.com/users/2900', 'pm_score': 11, 'selected': False, 'text': '<p>In your case, you can do:</p>\n<pre class="lang-py prettyprint-override"><code>z = dict(list(x.items()) + list(y.items()))\n</code></pre>\n<p>This will, as you want it, put the final dict in <code>z</code>, and make the value for key <code>b</code> be properly overridden by the second (<code>y</code>) dict\'s value:</p>\n<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; x = {\'a\':1, \'b\': 2}\n&gt;&gt;&gt; y = {\'b\':10, \'c\': 11}\n&gt;&gt;&gt; z = dict(list(x.items()) + list(y.items()))\n&gt;&gt;&gt; z\n{\'a\': 1, \'c\': 11, \'b\': 10}\n\n</code></pre>\n<p>If you use Python 2, you can even remove the <code>list()</code> calls. To create z:</p>\n<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; z = dict(x.items() + y.items())\n&gt;&gt;&gt; z\n{\'a\': 1, \'c\': 11, \'b\': 10}\n</code></pre>\n<p>If you use Python version 3.9.0a4 or greater, then you can directly use:</p>\n<pre class="lang-py prettyprint-override"><code>x = {\'a\':1, \'b\': 2}\ny = {\'b\':10, \'c\': 11}\nz = x | y\nprint(z)\n</code></pre>\n<pre class="lang-py prettyprint-override"><code>{\'a\': 1, \'c\': 11, \'b\': 10}\n</code></pre>\n'}, {'answer_id': 39437, 'author': 'Matthew Schinckel', 'author_id': 188, 'author_profile': 'https://Stackoverflow.com/users/188', 'pm_score': 10, 'selected': False, 'text': '<p>An alternative:</p>\n\n<pre><code>z = x.copy()\nz.update(y)\n</code></pre>\n'}, {'answer_id': 39858, 'author': 'Carl Meyer', 'author_id': 3207, 'author_profile': 'https://Stackoverflow.com/users/3207', 'pm_score': 9, 'selected': False, 'text': '<p>Another, more concise, option:</p>\n\n<pre><code>z = dict(x, **y)\n</code></pre>\n\n<p><strong>Note</strong>: this has become a popular answer, but it is important to point out that if <code>y</code> has any non-string keys, the fact that this works at all is an abuse of a CPython implementation detail, and it does not work in Python 3, or in PyPy, IronPython, or Jython. Also, <a href="http://mail.python.org/pipermail/python-dev/2010-April/099459.html" rel="noreferrer">Guido is not a fan</a>. So I can\'t recommend this technique for forward-compatible or cross-implementation portable code, which really means it should be avoided entirely.</p>\n'}, {'answer_id': 44512, 'author': 'rcreswick', 'author_id': 3446, 'author_profile': 'https://Stackoverflow.com/users/3446', 'pm_score': 7, 'selected': False, 'text': '<p>I wanted something similar, but with the ability to specify how the values on duplicate keys were merged, so I hacked this out (but did not heavily test it).  Obviously this is not a single expression, but it is a single function call.</p>\n\n<pre><code>def merge(d1, d2, merge_fn=lambda x,y:y):\n    """\n    Merges two dictionaries, non-destructively, combining \n    values on duplicate keys as defined by the optional merge\n    function.  The default behavior replaces the values in d1\n    with corresponding values in d2.  (There is no other generally\n    applicable merge strategy, but often you\'ll have homogeneous \n    types in your dicts, so specifying a merge technique can be \n    valuable.)\n\n    Examples:\n\n    &gt;&gt;&gt; d1\n    {\'a\': 1, \'c\': 3, \'b\': 2}\n    &gt;&gt;&gt; merge(d1, d1)\n    {\'a\': 1, \'c\': 3, \'b\': 2}\n    &gt;&gt;&gt; merge(d1, d1, lambda x,y: x+y)\n    {\'a\': 2, \'c\': 6, \'b\': 4}\n\n    """\n    result = dict(d1)\n    for k,v in d2.iteritems():\n        if k in result:\n            result[k] = merge_fn(result[k], v)\n        else:\n            result[k] = v\n    return result\n</code></pre>\n'}, {'answer_id': 49492, 'author': 'Tony Meyer', 'author_id': 4966, 'author_profile': 'https://Stackoverflow.com/users/4966', 'pm_score': 8, 'selected': False, 'text': '<p>This probably won\'t be a popular answer, but you almost certainly do not want to do this.  If you want a copy that\'s a merge, then use copy (or <a href="https://docs.python.org/2/library/copy.html" rel="noreferrer">deepcopy</a>, depending on what you want) and then update.  The two lines of code are much more readable - more Pythonic - than the single line creation with .items() + .items().  Explicit is better than implicit.</p>\n\n<p>In addition, when you use .items() (pre Python 3.0), you\'re creating a new list that contains the items from the dict.  If your dictionaries are large, then that is quite a lot of overhead (two large lists that will be thrown away as soon as the merged dict is created).  update() can work more efficiently, because it can run through the second dict item-by-item.</p>\n\n<p>In terms of <a href="https://docs.python.org/2/library/timeit.html" rel="noreferrer">time</a>:</p>\n\n<pre><code>&gt;&gt;&gt; timeit.Timer("dict(x, **y)", "x = dict(zip(range(1000), range(1000)))\\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000)\n15.52571702003479\n&gt;&gt;&gt; timeit.Timer("temp = x.copy()\\ntemp.update(y)", "x = dict(zip(range(1000), range(1000)))\\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000)\n15.694622993469238\n&gt;&gt;&gt; timeit.Timer("dict(x.items() + y.items())", "x = dict(zip(range(1000), range(1000)))\\ny=dict(zip(range(1000,2000), range(1000,2000)))").timeit(100000)\n41.484580039978027\n</code></pre>\n\n<p>IMO the tiny slowdown between the first two is worth it for the readability.  In addition, keyword arguments for dictionary creation was only added in Python 2.3, whereas copy() and update() will work in older versions.</p>\n'}, {'answer_id': 228366, 'author': 'zaphod', 'author_id': 13871, 'author_profile': 'https://Stackoverflow.com/users/13871', 'pm_score': 8, 'selected': False, 'text': '<p>In a follow-up answer, you asked about the relative performance of these two alternatives:</p>\n\n<pre><code>z1 = dict(x.items() + y.items())\nz2 = dict(x, **y)\n</code></pre>\n\n<p>On my machine, at least (a fairly ordinary x86_64 running Python 2.5.2), alternative <code>z2</code> is not only shorter and simpler but also significantly faster.  You can verify this for yourself using the <code>timeit</code> module that comes with Python.</p>\n\n<p>Example 1: identical dictionaries mapping 20 consecutive integers to themselves:</p>\n\n<pre><code>% python -m timeit -s \'x=y=dict((i,i) for i in range(20))\' \'z1=dict(x.items() + y.items())\'\n100000 loops, best of 3: 5.67 usec per loop\n% python -m timeit -s \'x=y=dict((i,i) for i in range(20))\' \'z2=dict(x, **y)\' \n100000 loops, best of 3: 1.53 usec per loop\n</code></pre>\n\n<p><code>z2</code> wins by a factor of 3.5 or so.  Different dictionaries seem to yield quite different results, but <code>z2</code> always seems to come out ahead.  (If you get inconsistent results for the <em>same</em> test, try passing in <code>-r</code> with a number larger than the default 3.)</p>\n\n<p>Example 2: non-overlapping dictionaries mapping 252 short strings to integers and vice versa:</p>\n\n<pre><code>% python -m timeit -s \'from htmlentitydefs import codepoint2name as x, name2codepoint as y\' \'z1=dict(x.items() + y.items())\'\n1000 loops, best of 3: 260 usec per loop\n% python -m timeit -s \'from htmlentitydefs import codepoint2name as x, name2codepoint as y\' \'z2=dict(x, **y)\'               \n10000 loops, best of 3: 26.9 usec per loop\n</code></pre>\n\n<p><code>z2</code> wins by about a factor of 10.  That\'s a pretty big win in my book!</p>\n\n<p>After comparing those two, I wondered if <code>z1</code>\'s poor performance could be attributed to the overhead of constructing the two item lists, which in turn led me to wonder if this variation might work better:</p>\n\n<pre><code>from itertools import chain\nz3 = dict(chain(x.iteritems(), y.iteritems()))\n</code></pre>\n\n<p>A few quick tests, e.g.</p>\n\n<pre><code>% python -m timeit -s \'from itertools import chain; from htmlentitydefs import codepoint2name as x, name2codepoint as y\' \'z3=dict(chain(x.iteritems(), y.iteritems()))\'\n10000 loops, best of 3: 66 usec per loop\n</code></pre>\n\n<p>lead me to conclude that <code>z3</code> is somewhat faster than <code>z1</code>, but not nearly as fast as <code>z2</code>.  Definitely not worth all the extra typing.</p>\n\n<p>This discussion is still missing something important, which is a performance comparison of these alternatives with the "obvious" way of merging two lists: using the <code>update</code> method.  To try to keep things on an equal footing with the expressions, none of which modify x or y, I\'m going to make a copy of x instead of modifying it in-place, as follows:</p>\n\n<pre><code>z0 = dict(x)\nz0.update(y)\n</code></pre>\n\n<p>A typical result:</p>\n\n<pre><code>% python -m timeit -s \'from htmlentitydefs import codepoint2name as x, name2codepoint as y\' \'z0=dict(x); z0.update(y)\'\n10000 loops, best of 3: 26.9 usec per loop\n</code></pre>\n\n<p>In other words, <code>z0</code> and <code>z2</code> seem to have essentially identical performance.  Do you think this might be a coincidence?  I don\'t....</p>\n\n<p>In fact, I\'d go so far as to claim that it\'s impossible for pure Python code to do any better than this.  And if you can do significantly better in a C extension module, I imagine the Python folks might well be interested in incorporating your code (or a variation on your approach) into the Python core.  Python uses <code>dict</code> in lots of places; optimizing its operations is a big deal.</p>\n\n<p>You could also write this as</p>\n\n<pre><code>z0 = x.copy()\nz0.update(y)\n</code></pre>\n\n<p>as Tony does, but (not surprisingly) the difference in notation turns out not to have any measurable effect on performance.  Use whichever looks right to you.  Of course, he\'s absolutely correct to point out that the two-statement version is much easier to understand.</p>\n'}, {'answer_id': 3936548, 'author': 'driax', 'author_id': 72476, 'author_profile': 'https://Stackoverflow.com/users/72476', 'pm_score': 7, 'selected': False, 'text': "<p>The best version I could think while not using copy would be:</p>\n\n<pre><code>from itertools import chain\nx = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\ndict(chain(x.iteritems(), y.iteritems()))\n</code></pre>\n\n<p>It's faster than <code>dict(x.items() + y.items())</code> but not as fast as <code>n = copy(a); n.update(b)</code>, at least on CPython. This version also works in Python 3 if you change <code>iteritems()</code> to <code>items()</code>, which is automatically done by the 2to3 tool.</p>\n\n<p>Personally I like this version best because it describes fairly good what I want in a single  functional syntax. The only minor problem is that it doesn't make completely obvious that values from y takes precedence over values from x, but I don't believe it's difficult to figure that out.</p>\n"}, {'answer_id': 7770473, 'author': 'phobie', 'author_id': 509648, 'author_profile': 'https://Stackoverflow.com/users/509648', 'pm_score': 6, 'selected': False, 'text': "<p>While the question has already been answered several times,\nthis simple solution to the problem has not been listed yet.</p>\n\n<pre><code>x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\nz4 = {}\nz4.update(x)\nz4.update(y)\n</code></pre>\n\n<p>It is as fast as z0 and the evil z2 mentioned above, but easy to understand and change.</p>\n"}, {'answer_id': 8247023, 'author': 'EMS', 'author_id': 364984, 'author_profile': 'https://Stackoverflow.com/users/364984', 'pm_score': 6, 'selected': False, 'text': "<p>If you think lambdas are evil then read no further.\nAs requested, you can write the fast and memory-efficient solution with one expression:</p>\n\n<pre><code>x = {'a':1, 'b':2}\ny = {'b':10, 'c':11}\nz = (lambda a, b: (lambda a_copy: a_copy.update(b) or a_copy)(a.copy()))(x, y)\nprint z\n{'a': 1, 'c': 11, 'b': 10}\nprint x\n{'a': 1, 'b': 2}\n</code></pre>\n\n<p>As suggested above, using two lines or writing a function is probably a better way to go.</p>\n"}, {'answer_id': 8310229, 'author': 'Stan', 'author_id': 471393, 'author_profile': 'https://Stackoverflow.com/users/471393', 'pm_score': 7, 'selected': False, 'text': '<h1>Recursively/deep update a dict</h1>\n\n<pre><code>def deepupdate(original, update):\n    """\n    Recursively update a dict.\n    Subdict\'s won\'t be overwritten but also updated.\n    """\n    for key, value in original.iteritems(): \n        if key not in update:\n            update[key] = value\n        elif isinstance(value, dict):\n            deepupdate(value, update[key]) \n    return update</code></pre>\n\n<p>Demonstration:</p>\n\n<pre><code>pluto_original = {\n    \'name\': \'Pluto\',\n    \'details\': {\n        \'tail\': True,\n        \'color\': \'orange\'\n    }\n}\n\npluto_update = {\n    \'name\': \'Pluutoo\',\n    \'details\': {\n        \'color\': \'blue\'\n    }\n}\n\nprint deepupdate(pluto_original, pluto_update)</code></pre>\n\n<p>Outputs:</p>\n\n<pre><code>{\n    \'name\': \'Pluutoo\',\n    \'details\': {\n        \'color\': \'blue\',\n        \'tail\': True\n    }\n}</code></pre>\n\n<p>Thanks rednaw for edits.</p>\n'}, {'answer_id': 11825563, 'author': 'Sam Watkins', 'author_id': 218294, 'author_profile': 'https://Stackoverflow.com/users/218294', 'pm_score': 6, 'selected': False, 'text': "<pre><code>def dict_merge(a, b):\n  c = a.copy()\n  c.update(b)\n  return c\n\nnew = dict_merge(old, extras)\n</code></pre>\n\n<p>Among such shady and dubious answers, this shining example is the one and only good way to merge dicts in Python, endorsed by dictator for life <em>Guido van Rossum</em> himself!  Someone else suggested half of this, but did not put it in a function.</p>\n\n<pre><code>print dict_merge(\n      {'color':'red', 'model':'Mini'},\n      {'model':'Ferrari', 'owner':'Carl'})\n</code></pre>\n\n<p>gives:</p>\n\n<pre><code>{'color': 'red', 'owner': 'Carl', 'model': 'Ferrari'}\n</code></pre>\n"}, {'answer_id': 12926103, 'author': 'Mathieu Larose', 'author_id': 122894, 'author_profile': 'https://Stackoverflow.com/users/122894', 'pm_score': 5, 'selected': False, 'text': '<p><strong>Two dictionaries</strong></p>\n\n<pre><code>def union2(dict1, dict2):\n    return dict(list(dict1.items()) + list(dict2.items()))\n</code></pre>\n\n<p><strong><em>n</em> dictionaries</strong></p>\n\n<pre><code>def union(*dicts):\n    return dict(itertools.chain.from_iterable(dct.items() for dct in dicts))\n</code></pre>\n\n<p><code>sum</code> has bad performance. See <a href="https://mathieularose.com/how-not-to-flatten-a-list-of-lists-in-python/" rel="noreferrer">https://mathieularose.com/how-not-to-flatten-a-list-of-lists-in-python/</a></p>\n'}, {'answer_id': 16259217, 'author': 'Raymond Hettinger', 'author_id': 424499, 'author_profile': 'https://Stackoverflow.com/users/424499', 'pm_score': 8, 'selected': False, 'text': '<p><strong>In Python 3.0 and later</strong>, you can use <a href="http://docs.python.org/3/library/collections.html#collections.ChainMap" rel="noreferrer"><code>collections.ChainMap</code></a> which groups multiple dicts or other mappings together to create a single, updateable view:</p>\n<pre><code>&gt;&gt;&gt; from collections import ChainMap\n&gt;&gt;&gt; x = {\'a\':1, \'b\': 2}\n&gt;&gt;&gt; y = {\'b\':10, \'c\': 11}\n&gt;&gt;&gt; z = dict(ChainMap({}, y, x))\n&gt;&gt;&gt; for k, v in z.items():\n        print(k, \'--&gt;\', v)\n    \na --&gt; 1\nb --&gt; 10\nc --&gt; 11\n</code></pre>\n<p><strong>Update for Python 3.5 and later</strong>: You can use <a href="https://www.python.org/dev/peps/pep-0448/" rel="noreferrer">PEP 448</a> extended dictionary packing and unpacking.  This is fast and easy:</p>\n<pre><code>&gt;&gt;&gt; x = {\'a\':1, \'b\': 2}\n&gt;&gt;&gt; y = {\'b\':10, \'c\': 11}\n&gt;&gt;&gt; {**x, **y}\n{\'a\': 1, \'b\': 10, \'c\': 11}\n</code></pre>\n<p><strong>Update for Python 3.9 and later</strong>:  You can use the <a href="https://www.python.org/dev/peps/pep-0584/" rel="noreferrer">PEP 584</a> union operator:</p>\n<pre><code>&gt;&gt;&gt; x = {\'a\':1, \'b\': 2}\n&gt;&gt;&gt; y = {\'b\':10, \'c\': 11}\n&gt;&gt;&gt; x | y\n{\'a\': 1, \'b\': 10, \'c\': 11}\n</code></pre>\n'}, {'answer_id': 16769722, 'author': 'kiriloff', 'author_id': 1141493, 'author_profile': 'https://Stackoverflow.com/users/1141493', 'pm_score': 3, 'selected': False, 'text': "<p>Using  a dict comprehension, you may</p>\n\n<pre><code>x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\n\ndc = {xi:(x[xi] if xi not in list(y.keys()) \n           else y[xi]) for xi in list(x.keys())+(list(y.keys()))}\n</code></pre>\n\n<p>gives</p>\n\n<pre><code>&gt;&gt;&gt; dc\n{'a': 1, 'c': 11, 'b': 10}\n</code></pre>\n\n<p>Note the syntax for <code>if else</code> in comprehension </p>\n\n<pre><code>{ (some_key if condition else default_key):(something_if_true if condition \n          else something_if_false) for key, value in dict_.items() }\n</code></pre>\n"}, {'answer_id': 17738920, 'author': 'Bijou Trouvaille', 'author_id': 375570, 'author_profile': 'https://Stackoverflow.com/users/375570', 'pm_score': 4, 'selected': False, 'text': "<p>Drawing on ideas here and elsewhere I've comprehended a function:</p>\n\n<pre><code>def merge(*dicts, **kv): \n      return { k:v for d in list(dicts) + [kv] for k,v in d.items() }\n</code></pre>\n\n<p>Usage (tested in python 3):</p>\n\n<pre><code>assert (merge({1:11,'a':'aaa'},{1:99, 'b':'bbb'},foo='bar')==\\\n    {1: 99, 'foo': 'bar', 'b': 'bbb', 'a': 'aaa'})\n\nassert (merge(foo='bar')=={'foo': 'bar'})\n\nassert (merge({1:11},{1:99},foo='bar',baz='quux')==\\\n    {1: 99, 'foo': 'bar', 'baz':'quux'})\n\nassert (merge({1:11},{1:99})=={1: 99})\n</code></pre>\n\n<p>You could use a lambda instead.</p>\n"}, {'answer_id': 18114065, 'author': 'Claudiu', 'author_id': 15055, 'author_profile': 'https://Stackoverflow.com/users/15055', 'pm_score': 5, 'selected': False, 'text': '<p>Abuse leading to a one-expression solution for <a href="https://stackoverflow.com/a/39437/15055">Matthew\'s answer</a>:</p>\n\n<pre><code>&gt;&gt;&gt; x = {\'a\':1, \'b\': 2}\n&gt;&gt;&gt; y = {\'b\':10, \'c\': 11}\n&gt;&gt;&gt; z = (lambda f=x.copy(): (f.update(y), f)[1])()\n&gt;&gt;&gt; z\n{\'a\': 1, \'c\': 11, \'b\': 10}\n</code></pre>\n\n<p>You said you wanted one expression, so I abused <code>lambda</code> to bind a name, and tuples to override lambda\'s one-expression limit. Feel free to cringe.</p>\n\n<p>You could also do this of course if you don\'t care about copying it:</p>\n\n<pre><code>&gt;&gt;&gt; x = {\'a\':1, \'b\': 2}\n&gt;&gt;&gt; y = {\'b\':10, \'c\': 11}\n&gt;&gt;&gt; z = (x.update(y), x)[1]\n&gt;&gt;&gt; z\n{\'a\': 1, \'b\': 10, \'c\': 11}\n</code></pre>\n'}, {'answer_id': 19279501, 'author': 'beardc', 'author_id': 386279, 'author_profile': 'https://Stackoverflow.com/users/386279', 'pm_score': 6, 'selected': False, 'text': '<p>In python3, the <code>items</code> method <a href="http://docs.python.org/dev/whatsnew/3.0.html#views-and-iterators-instead-of-lists" rel="noreferrer">no longer returns a list</a>, but rather a <em>view</em>, which acts like a set. In this case you\'ll need to take the set union since concatenating with <code>+</code> won\'t work:</p>\n\n<pre><code>dict(x.items() | y.items())\n</code></pre>\n\n<p>For python3-like behavior in version 2.7, the <code>viewitems</code> method should work in place of <code>items</code>:</p>\n\n<pre><code>dict(x.viewitems() | y.viewitems())\n</code></pre>\n\n<p>I prefer this notation anyways since it seems more natural to think of it as a set union operation rather than concatenation (as the title shows).</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>A couple more points for python 3. First, note that the <code>dict(x, **y)</code> trick won\'t work in python 3 unless the keys in <code>y</code> are strings.</p>\n\n<p>Also, Raymond Hettinger\'s Chainmap <a href="https://stackoverflow.com/a/16259217/386279">answer</a> is pretty elegant, since it can take an arbitrary number of dicts as arguments, but <a href="http://docs.python.org/dev/library/collections" rel="noreferrer">from the docs</a> it looks like it sequentially looks through a list of all the dicts for each lookup:</p>\n\n<blockquote>\n  <p>Lookups search the underlying mappings successively until a key is found.</p>\n</blockquote>\n\n<p>This can slow you down if you have a lot of lookups in your application:</p>\n\n<pre><code>In [1]: from collections import ChainMap\nIn [2]: from string import ascii_uppercase as up, ascii_lowercase as lo; x = dict(zip(lo, up)); y = dict(zip(up, lo))\nIn [3]: chainmap_dict = ChainMap(y, x)\nIn [4]: union_dict = dict(x.items() | y.items())\nIn [5]: timeit for k in union_dict: union_dict[k]\n100000 loops, best of 3: 2.15 µs per loop\nIn [6]: timeit for k in chainmap_dict: chainmap_dict[k]\n10000 loops, best of 3: 27.1 µs per loop\n</code></pre>\n\n<p>So about an order of magnitude slower for lookups. I\'m a fan of Chainmap, but looks less practical where there may be many lookups.</p>\n'}, {'answer_id': 19950727, 'author': 'John La Rooy', 'author_id': 174728, 'author_profile': 'https://Stackoverflow.com/users/174728', 'pm_score': 4, 'selected': False, 'text': "<pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2}\n&gt;&gt;&gt; y = {'b':10, 'c': 11}\n&gt;&gt;&gt; x, z = dict(x), x.update(y) or x\n&gt;&gt;&gt; x\n{'a': 1, 'b': 2}\n&gt;&gt;&gt; y\n{'c': 11, 'b': 10}\n&gt;&gt;&gt; z\n{'a': 1, 'c': 11, 'b': 10}\n</code></pre>\n"}, {'answer_id': 20358548, 'author': 'upandacross', 'author_id': 3062691, 'author_profile': 'https://Stackoverflow.com/users/3062691', 'pm_score': 4, 'selected': False, 'text': '<p>The problem I have with solutions listed to date is that, in the merged dictionary, the value for key "b" is 10 but, to my way of thinking, it should be 12.\nIn that light, I present the following:</p>\n\n<pre><code>import timeit\n\nn=100000\nsu = """\nx = {\'a\':1, \'b\': 2}\ny = {\'b\':10, \'c\': 11}\n"""\n\ndef timeMerge(f,su,niter):\n    print "{:4f} sec for: {:30s}".format(timeit.Timer(f,setup=su).timeit(n),f)\n\ntimeMerge("dict(x, **y)",su,n)\ntimeMerge("x.update(y)",su,n)\ntimeMerge("dict(x.items() + y.items())",su,n)\ntimeMerge("for k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k] ",su,n)\n\n#confirm for loop adds b entries together\nx = {\'a\':1, \'b\': 2}\ny = {\'b\':10, \'c\': 11}\nfor k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k]\nprint "confirm b elements are added:",x\n</code></pre>\n\n<h1>Results:</h1>\n\n<pre><code>0.049465 sec for: dict(x, **y)\n0.033729 sec for: x.update(y)                   \n0.150380 sec for: dict(x.items() + y.items())   \n0.083120 sec for: for k in y.keys(): x[k] = k in x and x[k]+y[k] or y[k]\n\nconfirm b elements are added: {\'a\': 1, \'c\': 11, \'b\': 12}\n</code></pre>\n'}, {'answer_id': 22122836, 'author': 'GetFree', 'author_id': 25700, 'author_profile': 'https://Stackoverflow.com/users/25700', 'pm_score': 4, 'selected': False, 'text': "<p>It's so silly that <code>.update</code> returns nothing.<br>\nI just use a simple helper function to solve the problem:</p>\n\n<pre><code>def merge(dict1,*dicts):\n    for dict2 in dicts:\n        dict1.update(dict2)\n    return dict1\n</code></pre>\n\n<p>Examples:</p>\n\n<pre><code>merge(dict1,dict2)\nmerge(dict1,dict2,dict3)\nmerge(dict1,dict2,dict3,dict4)\nmerge({},dict1,dict2)  # this one returns a new copy\n</code></pre>\n"}, {'answer_id': 26111877, 'author': 'bassounds', 'author_id': 3169972, 'author_profile': 'https://Stackoverflow.com/users/3169972', 'pm_score': 3, 'selected': False, 'text': "<p>A union of the OP's two dictionaries would be something like:</p>\n\n<pre><code>{'a': 1, 'b': 2, 10, 'c': 11}\n</code></pre>\n\n<p>Specifically, the union of two entities(<code>x</code> and <code>y</code>) contains all the elements of <code>x</code> and/or <code>y</code>.\nUnfortunately, what the OP asks for is not a union, despite the title of the post.</p>\n\n<p>My code below is neither elegant nor a one-liner, but I believe it is consistent with the meaning of union.</p>\n\n<p>From the OP's example:</p>\n\n<pre><code>x = {'a':1, 'b': 2}\ny = {'b':10, 'c': 11}\n\nz = {}\nfor k, v in x.items():\n    if not k in z:\n        z[k] = [(v)]\n    else:\n        z[k].append((v))\nfor k, v in y.items():\n    if not k in z:\n        z[k] = [(v)]\n    else:\n        z[k].append((v))\n\n{'a': [1], 'b': [2, 10], 'c': [11]}\n</code></pre>\n\n<p>Whether one wants lists could be changed, but the above will work if a dictionary contains lists (and nested lists) as values in either dictionary.</p>\n"}, {'answer_id': 26853961, 'author': 'Russia Must Remove Putin', 'author_id': 541136, 'author_profile': 'https://Stackoverflow.com/users/541136', 'pm_score': 14, 'selected': True, 'text': '<h2>How can I merge two Python dictionaries in a single expression?</h2>\n<p>For dictionaries <code>x</code> and <code>y</code>, their shallowly-merged dictionary <code>z</code> takes values from <code>y</code>, replacing those from <code>x</code>.</p>\n<ul>\n<li><p>In Python 3.9.0 or greater (released 17 October 2020, <a href="https://www.python.org/dev/peps/pep-0584/" rel="noreferrer"><code>PEP-584</code></a>, <a href="https://bugs.python.org/issue36144" rel="noreferrer">discussed here</a>):</p>\n<pre class="lang-py prettyprint-override"><code>z = x | y\n</code></pre>\n</li>\n<li><p>In Python 3.5 or greater:</p>\n<pre class="lang-py prettyprint-override"><code>z = {**x, **y}\n</code></pre>\n</li>\n<li><p>In Python 2, (or 3.4 or lower) write a function:</p>\n<pre class="lang-py prettyprint-override"><code>def merge_two_dicts(x, y):\n    z = x.copy()   # start with keys and values of x\n    z.update(y)    # modifies z with keys and values of y\n    return z\n</code></pre>\n<p>and now:</p>\n<pre class="lang-py prettyprint-override"><code>z = merge_two_dicts(x, y)\n</code></pre>\n</li>\n</ul>\n<h3>Explanation</h3>\n<p>Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries:</p>\n<pre class="lang-py prettyprint-override"><code>x = {\'a\': 1, \'b\': 2}\ny = {\'b\': 3, \'c\': 4}\n</code></pre>\n<p>The desired result is to get a new dictionary (<code>z</code>) with the values merged, and the second dictionary\'s values overwriting those from the first.</p>\n<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; z\n{\'a\': 1, \'b\': 3, \'c\': 4}\n</code></pre>\n<p>A new syntax for this, proposed in <a href="https://www.python.org/dev/peps/pep-0448" rel="noreferrer">PEP 448</a> and <a href="https://mail.python.org/pipermail/python-dev/2015-February/138564.html" rel="noreferrer">available as of Python 3.5</a>, is</p>\n<pre class="lang-py prettyprint-override"><code>z = {**x, **y}\n</code></pre>\n<p>And it is indeed a single expression.</p>\n<p>Note that we can merge in with literal notation as well:</p>\n<pre class="lang-py prettyprint-override"><code>z = {**x, \'foo\': 1, \'bar\': 2, **y}\n</code></pre>\n<p>and now:</p>\n<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; z\n{\'a\': 1, \'b\': 3, \'foo\': 1, \'bar\': 2, \'c\': 4}\n</code></pre>\n<p>It is now showing as implemented in the <a href="https://www.python.org/dev/peps/pep-0478/#features-for-3-5" rel="noreferrer">release schedule for 3.5, PEP 478</a>, and it has now made its way into the <a href="https://docs.python.org/dev/whatsnew/3.5.html#pep-448-additional-unpacking-generalizations" rel="noreferrer">What\'s New in Python 3.5</a> document.</p>\n<p>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:</p>\n<pre class="lang-py prettyprint-override"><code>z = x.copy()\nz.update(y) # which returns None since it mutates z\n</code></pre>\n<p>In both approaches, <code>y</code> will come second and its values will replace <code>x</code>\'s values, thus <code>b</code> will point to <code>3</code> in our final result.</p>\n<h2>Not yet on Python 3.5, but want a <em>single expression</em></h2>\n<p>If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a <em>single expression</em>, the most performant while the correct approach is to put it in a function:</p>\n<pre class="lang-py prettyprint-override"><code>def merge_two_dicts(x, y):\n    &quot;&quot;&quot;Given two dictionaries, merge them into a new dict as a shallow copy.&quot;&quot;&quot;\n    z = x.copy()\n    z.update(y)\n    return z\n</code></pre>\n<p>and then you have a single expression:</p>\n<pre class="lang-py prettyprint-override"><code>z = merge_two_dicts(x, y)\n</code></pre>\n<p>You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number:</p>\n<pre class="lang-py prettyprint-override"><code>def merge_dicts(*dict_args):\n    &quot;&quot;&quot;\n    Given any number of dictionaries, shallow copy and merge into a new dict,\n    precedence goes to key-value pairs in latter dictionaries.\n    &quot;&quot;&quot;\n    result = {}\n    for dictionary in dict_args:\n        result.update(dictionary)\n    return result\n</code></pre>\n<p>This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries <code>a</code> to <code>g</code>:</p>\n<pre class="lang-py prettyprint-override"><code>z = merge_dicts(a, b, c, d, e, f, g) \n</code></pre>\n<p>and key-value pairs in <code>g</code> will take precedence over dictionaries <code>a</code> to <code>f</code>, and so on.</p>\n<h2>Critiques of Other Answers</h2>\n<p>Don\'t use what you see in the formerly accepted answer:</p>\n<pre class="lang-py prettyprint-override"><code>z = dict(x.items() + y.items())\n</code></pre>\n<p>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. <strong>In Python 3, this will fail</strong> because you\'re adding two <code>dict_items</code> objects together, not two lists -</p>\n<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; c = dict(a.items() + b.items())\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nTypeError: unsupported operand type(s) for +: \'dict_items\' and \'dict_items\'\n</code></pre>\n<p>and you would have to explicitly create them as lists, e.g. <code>z = dict(list(x.items()) + list(y.items()))</code>. This is a waste of resources and computation power.</p>\n<p>Similarly, taking the union of <code>items()</code> in Python 3 (<code>viewitems()</code> in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, <strong>since sets are semantically unordered, the behavior is undefined in regards to precedence. So don\'t do this:</strong></p>\n<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; c = dict(a.items() | b.items())\n</code></pre>\n<p>This example demonstrates what happens when values are unhashable:</p>\n<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; x = {\'a\': []}\n&gt;&gt;&gt; y = {\'b\': []}\n&gt;&gt;&gt; dict(x.items() | y.items())\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nTypeError: unhashable type: \'list\'\n</code></pre>\n<p>Here\'s an example where <code>y</code> should have precedence, but instead the value from <code>x</code> is retained due to the arbitrary order of sets:</p>\n<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; x = {\'a\': 2}\n&gt;&gt;&gt; y = {\'a\': 1}\n&gt;&gt;&gt; dict(x.items() | y.items())\n{\'a\': 2}\n</code></pre>\n<p>Another hack you should not use:</p>\n<pre class="lang-py prettyprint-override"><code>z = dict(x, **y)\n</code></pre>\n<p>This uses the <code>dict</code> 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.</p>\n<p>Here\'s an example of the usage being <a href="https://code.djangoproject.com/attachment/ticket/13357/django-pypy.2.diff" rel="noreferrer">remediated in django</a>.</p>\n<p>Dictionaries are intended to take hashable keys (e.g. <code>frozenset</code>s or tuples), but <strong>this method fails in Python 3 when keys are not strings.</strong></p>\n<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; c = dict(a, **b)\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nTypeError: keyword arguments must be strings\n</code></pre>\n<p>From the <a href="https://mail.python.org/pipermail/python-dev/2010-April/099459.html" rel="noreferrer">mailing list</a>, Guido van Rossum, the creator of the language, wrote:</p>\n<blockquote>\n<p>I am fine with\ndeclaring dict({}, **{1:3}) illegal, since after all it is abuse of\nthe ** mechanism.</p>\n</blockquote>\n<p>and</p>\n<blockquote>\n<p>Apparently dict(x, **y) is going around as &quot;cool hack&quot; for &quot;call\nx.update(y) and return x&quot;. Personally, I find it more despicable than\ncool.</p>\n</blockquote>\n<p>It is my understanding (as well as the understanding of the <a href="https://mail.python.org/pipermail/python-dev/2010-April/099485.html" rel="noreferrer">creator of the language</a>) that the intended usage for <code>dict(**y)</code> is for creating dictionaries for readability purposes, e.g.:</p>\n<pre class="lang-py prettyprint-override"><code>dict(a=1, b=10, c=11)\n</code></pre>\n<p>instead of</p>\n<pre class="lang-py prettyprint-override"><code>{\'a\': 1, \'b\': 10, \'c\': 11}\n</code></pre>\n<h2>Response to comments</h2>\n<blockquote>\n<p>Despite what Guido says, <code>dict(x, **y)</code> 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.</p>\n</blockquote>\n<p>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. <code>dict</code> broke this consistency in Python 2:</p>\n<pre><code>&gt;&gt;&gt; foo(**{(\'a\', \'b\'): None})\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nTypeError: foo() keywords must be strings\n&gt;&gt;&gt; dict(**{(\'a\', \'b\'): None})\n{(\'a\', \'b\'): None}\n</code></pre>\n<p>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.</p>\n<p>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.</p>\n<p>More comments:</p>\n<blockquote>\n<p><code>dict(x.items() + y.items())</code> is still the most readable solution for Python 2. Readability counts.</p>\n</blockquote>\n<p>My response: <code>merge_two_dicts(x, y)</code> 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.</p>\n<blockquote>\n<p><code>{**x, **y}</code> 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 &quot;merging&quot; these answers describe &quot;updating one dict with another&quot;, and not merging.</p>\n</blockquote>\n<p>Yes. I must refer you back to the question, which is asking for a <em>shallow</em> merge of <em><strong>two</strong></em> dictionaries, with the first\'s values being overwritten by the second\'s - in a single expression.</p>\n<p>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:</p>\n<pre class="lang-py prettyprint-override"><code>from copy import deepcopy\n\ndef dict_of_dicts_merge(x, y):\n    z = {}\n    overlapping_keys = x.keys() &amp; y.keys()\n    for key in overlapping_keys:\n        z[key] = dict_of_dicts_merge(x[key], y[key])\n    for key in x.keys() - overlapping_keys:\n        z[key] = deepcopy(x[key])\n    for key in y.keys() - overlapping_keys:\n        z[key] = deepcopy(y[key])\n    return z\n</code></pre>\n<p>Usage:</p>\n<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; x = {\'a\':{1:{}}, \'b\': {2:{}}}\n&gt;&gt;&gt; y = {\'b\':{10:{}}, \'c\': {11:{}}}\n&gt;&gt;&gt; dict_of_dicts_merge(x, y)\n{\'b\': {2: {}, 10: {}}, \'a\': {1: {}}, \'c\': {11: {}}}\n</code></pre>\n<p>Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at <a href="https://stackoverflow.com/a/24088493/541136">my answer to the canonical question on a &quot;Dictionaries of dictionaries merge&quot;</a>.</p>\n<h2>Less Performant But Correct Ad-hocs</h2>\n<p>These approaches are less performant, but they will provide correct behavior.\nThey will be <em>much less</em> performant than <code>copy</code> and <code>update</code> or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they <em>do</em> respect the order of precedence (latter dictionaries have precedence)</p>\n<p>You can also chain the dictionaries manually inside a <a href="https://www.python.org/dev/peps/pep-0274/" rel="noreferrer">dict comprehension</a>:</p>\n<pre class="lang-py prettyprint-override"><code>{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7\n</code></pre>\n<p>or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):</p>\n<pre class="lang-py prettyprint-override"><code>dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2\n</code></pre>\n<p><code>itertools.chain</code> will chain the iterators over the key-value pairs in the correct order:</p>\n<pre class="lang-py prettyprint-override"><code>from itertools import chain\nz = dict(chain(x.items(), y.items())) # iteritems in Python 2\n</code></pre>\n<h2>Performance Analysis</h2>\n<p>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.)</p>\n<pre class="lang-py prettyprint-override"><code>from timeit import repeat\nfrom itertools import chain\n\nx = dict.fromkeys(\'abcdefg\')\ny = dict.fromkeys(\'efghijk\')\n\ndef merge_two_dicts(x, y):\n    z = x.copy()\n    z.update(y)\n    return z\n\nmin(repeat(lambda: {**x, **y}))\nmin(repeat(lambda: merge_two_dicts(x, y)))\nmin(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))\nmin(repeat(lambda: dict(chain(x.items(), y.items()))))\nmin(repeat(lambda: dict(item for d in (x, y) for item in d.items())))\n</code></pre>\n<p>In Python 3.8.1, NixOS:</p>\n<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; min(repeat(lambda: {**x, **y}))\n1.0804965235292912\n&gt;&gt;&gt; min(repeat(lambda: merge_two_dicts(x, y)))\n1.636518670246005\n&gt;&gt;&gt; min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))\n3.1779992282390594\n&gt;&gt;&gt; min(repeat(lambda: dict(chain(x.items(), y.items()))))\n2.740647904574871\n&gt;&gt;&gt; min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))\n4.266070580109954\n</code></pre>\n<pre class="lang-sh prettyprint-override"><code>$ uname -a\nLinux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux\n</code></pre>\n<h2>Resources on Dictionaries</h2>\n<ul>\n<li><a href="https://stackoverflow.com/questions/327311/how-are-pythons-built-in-dictionaries-implemented/44509302#44509302">My explanation of Python\'s <strong>dictionary implementation</strong>, updated for 3.6.</a></li>\n<li><a href="https://stackoverflow.com/questions/1024847/add-new-keys-to-a-dictionary/27208535#27208535">Answer on how to add new keys to a dictionary</a></li>\n<li><a href="https://stackoverflow.com/questions/209840/map-two-lists-into-a-dictionary-in-python/33737067#33737067">Mapping two lists into a dictionary</a></li>\n<li><a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="noreferrer">The official Python docs on dictionaries</a></li>\n<li><a href="https://www.youtube.com/watch?v=66P5FMkWoVU" rel="noreferrer">The Dictionary Even Mightier</a> - talk by Brandon Rhodes at Pycon 2017</li>\n<li><a href="https://www.youtube.com/watch?v=npw4s1QTmPg" rel="noreferrer">Modern Python Dictionaries, A Confluence of Great Ideas</a> - talk by Raymond Hettinger at Pycon 2017</li>\n</ul>\n'}, {'answer_id': 28753078, 'author': 'Bilal Syed Hussain', 'author_id': 852240, 'author_profile': 'https://Stackoverflow.com/users/852240', 'pm_score': 7, 'selected': False, 'text': "<p>Python 3.5 (PEP 448) allows a nicer syntax option:</p>\n\n<pre><code>x = {'a': 1, 'b': 1}\ny = {'a': 2, 'c': 2}\nfinal = {**x, **y} \nfinal\n# {'a': 2, 'b': 1, 'c': 2}\n</code></pre>\n\n<p>Or even </p>\n\n<pre><code>final = {'a': 1, 'b': 1, **x, **y}\n</code></pre>\n\n<p>In Python 3.9 you also use | and |= with the below example from PEP 584</p>\n\n<pre><code>d = {'spam': 1, 'eggs': 2, 'cheese': 3}\ne = {'cheese': 'cheddar', 'aardvark': 'Ethel'}\nd | e\n# {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}\n</code></pre>\n"}, {'answer_id': 31478567, 'author': 'RemcoGerlich', 'author_id': 799163, 'author_profile': 'https://Stackoverflow.com/users/799163', 'pm_score': 4, 'selected': False, 'text': "<p>This can be done with a single dict comprehension:</p>\n\n<pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2}\n&gt;&gt;&gt; y = {'b':10, 'c': 11}\n&gt;&gt;&gt; { key: y[key] if key in y else x[key]\n      for key in set(x) + set(y)\n    }\n</code></pre>\n\n<p>In my view the best answer for the 'single expression' part as no extra functions are needed, and it is short.</p>\n"}, {'answer_id': 31812635, 'author': 'reubano', 'author_id': 408556, 'author_profile': 'https://Stackoverflow.com/users/408556', 'pm_score': 5, 'selected': False, 'text': "<p>Simple solution using itertools that preserves order (latter dicts have precedence)</p>\n<pre><code># py2\nfrom itertools import chain, imap\nmerge = lambda *args: dict(chain.from_iterable(imap(dict.iteritems, args)))\n\n# py3\nfrom itertools import chain\nmerge = lambda *args: dict(chain.from_iterable(map(dict.items, args)))\n</code></pre>\n<p>And it's usage:</p>\n<pre><code>&gt;&gt;&gt; x = {'a':1, 'b': 2}\n&gt;&gt;&gt; y = {'b':10, 'c': 11}\n&gt;&gt;&gt; merge(x, y)\n{'a': 1, 'b': 10, 'c': 11}\n\n&gt;&gt;&gt; z = {'c': 3, 'd': 4}\n&gt;&gt;&gt; merge(x, y, z)\n{'a': 1, 'b': 10, 'c': 3, 'd': 4}\n</code></pre>\n"}, {'answer_id': 33999337, 'author': 'reetesh11', 'author_id': 3145137, 'author_profile': 'https://Stackoverflow.com/users/3145137', 'pm_score': 4, 'selected': False, 'text': "<pre><code>from collections import Counter\ndict1 = {'a':1, 'b': 2}\ndict2 = {'b':10, 'c': 11}\nresult = dict(Counter(dict1) + Counter(dict2))\n</code></pre>\n\n<p>This should solve your problem.</p>\n"}, {'answer_id': 34899183, 'author': 'Robino', 'author_id': 833208, 'author_profile': 'https://Stackoverflow.com/users/833208', 'pm_score': 6, 'selected': False, 'text': '<p>Be Pythonic. Use a <a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries" rel="nofollow noreferrer">comprehension</a>:</p>\n<pre><code>z={k: v for d in [x,y] for k, v in d.items()}\n\n&gt;&gt;&gt; print z\n{\'a\': 1, \'c\': 11, \'b\': 10}\n</code></pre>\n'}, {'answer_id': 36263150, 'author': 'kjo', 'author_id': 559827, 'author_profile': 'https://Stackoverflow.com/users/559827', 'pm_score': 4, 'selected': False, 'text': "<p>(For Python\xa02.7* only; there are simpler solutions for Python\xa03*.)</p>\n<p>If you're not averse to importing a standard library module, you can do</p>\n<pre><code>from functools import reduce\n\ndef merge_dicts(*dicts):\n    return reduce(lambda a, d: a.update(d) or a, dicts, {})\n</code></pre>\n<p>(The <code>or a</code> bit in the <code>lambda</code> is necessary because <code>dict.update</code> always returns <code>None</code> on success.)</p>\n"}, {'answer_id': 37304637, 'author': 'Alfe', 'author_id': 1281485, 'author_profile': 'https://Stackoverflow.com/users/1281485', 'pm_score': 3, 'selected': False, 'text': '<p>I know this does not really fit the specifics of the questions ("one liner"), but since <em>none</em> of the answers above went into this direction while lots and lots of answers addressed the performance issue, I felt I should contribute my thoughts.</p>\n\n<p>Depending on the use case it might not be necessary to create a "real" merged dictionary of the given input dictionaries.  A <em>view</em> which does this might be sufficient in many cases, i. e. an object which acts <em>like</em> the merged dictionary would without computing it completely.  A lazy version of the merged dictionary, so to speak.</p>\n\n<p>In Python, this is rather simple and can be done with the code shown at the end of my post.  This given, the answer to the original question would be:</p>\n\n<pre><code>z = MergeDict(x, y)\n</code></pre>\n\n<p>When using this new object, it will behave like a merged dictionary but it will have constant creation time and constant memory footprint while leaving the original dictionaries untouched.  Creating it is way cheaper than in the other solutions proposed.</p>\n\n<p>Of course, if you use the result a lot, then you will at some point reach the limit where creating a real merged dictionary would have been the faster solution.  As I said, it depends on your use case.</p>\n\n<p>If you ever felt you would prefer to have a real merged <code>dict</code>, then calling <code>dict(z)</code> would produce it (but way more costly than the other solutions of course, so this is just worth mentioning).</p>\n\n<p>You can also use this class to make a kind of copy-on-write dictionary:</p>\n\n<pre><code>a = { \'x\': 3, \'y\': 4 }\nb = MergeDict(a)  # we merge just one dict\nb[\'x\'] = 5\nprint b  # will print {\'x\': 5, \'y\': 4}\nprint a  # will print {\'y\': 4, \'x\': 3}\n</code></pre>\n\n<p>Here\'s the straight-forward code of <code>MergeDict</code>:</p>\n\n<pre><code>class MergeDict(object):\n  def __init__(self, *originals):\n    self.originals = ({},) + originals[::-1]  # reversed\n\n  def __getitem__(self, key):\n    for original in self.originals:\n      try:\n        return original[key]\n      except KeyError:\n        pass\n    raise KeyError(key)\n\n  def __setitem__(self, key, value):\n    self.originals[0][key] = value\n\n  def __iter__(self):\n    return iter(self.keys())\n\n  def __repr__(self):\n    return \'%s(%s)\' % (\n      self.__class__.__name__,\n      \', \'.join(repr(original)\n          for original in reversed(self.originals)))\n\n  def __str__(self):\n    return \'{%s}\' % \', \'.join(\n        \'%r: %r\' % i for i in self.iteritems())\n\n  def iteritems(self):\n    found = set()\n    for original in self.originals:\n      for k, v in original.iteritems():\n        if k not in found:\n          yield k, v\n          found.add(k)\n\n  def items(self):\n    return list(self.iteritems())\n\n  def keys(self):\n    return list(k for k, _ in self.iteritems())\n\n  def values(self):\n    return list(v for _, v in self.iteritems())\n</code></pre>\n'}, {'answer_id': 40677646, 'author': 'Mike Graham', 'author_id': 192839, 'author_profile': 'https://Stackoverflow.com/users/192839', 'pm_score': 3, 'selected': False, 'text': '<p>You can use <a href="http://toolz.readthedocs.io/en/latest/api.html#toolz.dicttoolz.merge" rel="nofollow noreferrer"><code>toolz.merge([x, y])</code></a> for this.</p>\n'}, {'answer_id': 44262317, 'author': 'gboffi', 'author_id': 2749397, 'author_profile': 'https://Stackoverflow.com/users/2749397', 'pm_score': 0, 'selected': False, 'text': '<p>The question is tagged <code>python-3x</code> but, taking into account that it\'s a relatively recent addition and that the most voted, accepted answer deals extensively with a Python 2.x solution, I dare add a one liner that draws on an irritating feature of Python 2.x list comprehension, that is <em>name leaking</em>...</p>\n\n<pre><code>$ python2\nPython 2.7.13 (default, Jan 19 2017, 14:48:08) \n[GCC 6.3.0 20170118] on linux2\nType "help", "copyright", "credits" or "license" for more information.\n&gt;&gt;&gt; x = {\'a\':1, \'b\': 2}\n&gt;&gt;&gt; y = {\'b\':10, \'c\': 11}\n&gt;&gt;&gt; [z.update(d) for z in [{}] for d in (x, y)]\n[None, None]\n&gt;&gt;&gt; z\n{\'a\': 1, \'c\': 11, \'b\': 10}\n&gt;&gt;&gt; ...\n</code></pre>\n\n<p>I\'m happy to say that the above doesn\'t work any more on any version of Python 3.</p>\n'}, {'answer_id': 46356150, 'author': 'gilch', 'author_id': 4381487, 'author_profile': 'https://Stackoverflow.com/users/4381487', 'pm_score': 5, 'selected': False, 'text': '<p>If you don\'t mind mutating <code>x</code>,</p>\n<pre><code>x.update(y) or x\n</code></pre>\n<p>Simple, readable, performant. You <em>know</em> <code>update()</code> always returns <code>None</code>, which is a false value. So the above expression will always evaluate to <code>x</code>, after updating it.</p>\n<p>Most mutating methods in the standard library (like <code>.update()</code>) return <code>None</code> by convention, so this kind of pattern will work on those too. However, if you\'re using a dict subclass or some other method that doesn\'t follow this convention, then <code>or</code> may return its left operand, which may not be what you want. Instead, you can use a tuple display and index, which works regardless of what the first element evaluates to (although it\'s not quite as pretty):</p>\n<pre><code>(x.update(y), x)[-1]\n</code></pre>\n<p>If you don\'t have <code>x</code> in a variable yet, you can use <code>lambda</code> to make a local without using an assignment statement. This amounts to using <code>lambda</code> as a <em>let expression</em>, which is a common technique in functional languages, but is maybe unpythonic.</p>\n<pre><code>(lambda x: x.update(y) or x)({\'a\': 1, \'b\': 2})\n</code></pre>\n<p>Although it\'s not that different from the following use of the new walrus operator (Python 3.8+ only),</p>\n<pre><code>(x := {\'a\': 1, \'b\': 2}).update(y) or x\n</code></pre>\n<p>especially if you use a default argument:</p>\n<pre><code>(lambda x={\'a\': 1, \'b\': 2}: x.update(y) or x)()\n</code></pre>\n<p>If you do want a copy, <a href="https://www.python.org/dev/peps/pep-0584/" rel="noreferrer">PEP 584</a> style <code>x | y</code> is the most Pythonic on 3.9+. If you must support older versions, <a href="https://www.python.org/dev/peps/pep-0448/" rel="noreferrer">PEP 448</a> style <code>{**x, **y}</code> is easiest for 3.5+. But if that\'s not available in your (even older) Python version, the <em>let expression</em> pattern works here too.</p>\n<pre><code>(lambda z=x.copy(): z.update(y) or z)()\n</code></pre>\n<p>(That is, of course, nearly equivalent to <code>(z := x.copy()).update(y) or z</code>, but if your Python version is new enough for that, then the PEP 448 style will be available.)</p>\n'}, {'answer_id': 49420387, 'author': 'litepresence', 'author_id': 3680588, 'author_profile': 'https://Stackoverflow.com/users/3680588', 'pm_score': 3, 'selected': False, 'text': '<p>I was curious if I could beat the accepted answer\'s time with a one line stringify approach:</p>\n\n<p>I tried 5 methods, none previously mentioned - all one liner - all producing correct answers - and I couldn\'t come close.</p>\n\n<p>So... to save you the trouble and perhaps fulfill curiosity:</p>\n\n<pre><code>import json\nimport yaml\nimport time\nfrom ast import literal_eval as literal\n\ndef merge_two_dicts(x, y):\n    z = x.copy()   # start with x\'s keys and values\n    z.update(y)    # modifies z with y\'s keys and values &amp; returns None\n    return z\n\nx = {\'a\':1, \'b\': 2}\ny = {\'b\':10, \'c\': 11}\n\nstart = time.time()\nfor i in range(10000):\n    z = yaml.load((str(x)+str(y)).replace(\'}{\',\', \'))\nelapsed = (time.time()-start)\nprint (elapsed, z, \'stringify yaml\')\n\nstart = time.time()\nfor i in range(10000):\n    z = literal((str(x)+str(y)).replace(\'}{\',\', \'))\nelapsed = (time.time()-start)\nprint (elapsed, z, \'stringify literal\')\n\nstart = time.time()\nfor i in range(10000):\n    z = eval((str(x)+str(y)).replace(\'}{\',\', \'))\nelapsed = (time.time()-start)\nprint (elapsed, z, \'stringify eval\')\n\nstart = time.time()\nfor i in range(10000):\n    z = {k:int(v) for k,v in (dict(zip(\n            ((str(x)+str(y))\n            .replace(\'}\',\' \')\n            .replace(\'{\',\' \')\n            .replace(\':\',\' \')\n            .replace(\',\',\' \')\n            .replace("\'",\'\')\n            .strip()\n            .split(\'  \'))[::2], \n            ((str(x)+str(y))\n            .replace(\'}\',\' \')\n            .replace(\'{\',\' \').replace(\':\',\' \')\n            .replace(\',\',\' \')\n            .replace("\'",\'\')\n            .strip()\n            .split(\'  \'))[1::2]\n             ))).items()}\nelapsed = (time.time()-start)\nprint (elapsed, z, \'stringify replace\')\n\nstart = time.time()\nfor i in range(10000):\n    z = json.loads(str((str(x)+str(y)).replace(\'}{\',\', \').replace("\'",\'"\')))\nelapsed = (time.time()-start)\nprint (elapsed, z, \'stringify json\')\n\nstart = time.time()\nfor i in range(10000):\n    z = merge_two_dicts(x, y)\nelapsed = (time.time()-start)\nprint (elapsed, z, \'accepted\')\n</code></pre>\n\n<p>results:</p>\n\n<pre><code>7.693928956985474 {\'c\': 11, \'b\': 10, \'a\': 1} stringify yaml\n0.29134678840637207 {\'c\': 11, \'b\': 10, \'a\': 1} stringify literal\n0.2208399772644043 {\'c\': 11, \'b\': 10, \'a\': 1} stringify eval\n0.1106564998626709 {\'c\': 11, \'b\': 10, \'a\': 1} stringify replace\n0.07989692687988281 {\'c\': 11, \'b\': 10, \'a\': 1} stringify json\n0.005082368850708008 {\'c\': 11, \'b\': 10, \'a\': 1} accepted\n</code></pre>\n\n<p>What I did learn from this is that JSON approach is the fastest way (of those attempted) to return a dictionary from string-of-dictionary; much faster (about 1/4th of the time) of what I considered to be the normal method using <code>ast</code>.  I also learned that, the YAML approach should be avoided at all cost.</p>\n\n<p>Yes, I understand that this is not the best/correct way. I was curious if it was faster, and it isn\'t; I posted to prove it so.</p>\n'}, {'answer_id': 49847631, 'author': 'Josh Bode', 'author_id': 182469, 'author_profile': 'https://Stackoverflow.com/users/182469', 'pm_score': 3, 'selected': False, 'text': "<p>This is an expression for Python 3.5 or greater that merges dictionaries using <code>reduce</code>:</p>\n<pre><code>&gt;&gt;&gt; from functools import reduce\n&gt;&gt;&gt; l = [{'a': 1}, {'b': 2}, {'a': 100, 'c': 3}]\n&gt;&gt;&gt; reduce(lambda x, y: {**x, **y}, l, {})\n{'a': 100, 'b': 2, 'c': 3}\n</code></pre>\n<p>Note: this works even if the dictionary list is empty or contains only one element.</p>\n<p>For a more efficient merge on Python 3.9 or greater, the <code>lambda</code> can be replaced directly by <code>operator.ior</code>:</p>\n<pre><code>&gt;&gt;&gt; from functools import reduce\n&gt;&gt;&gt; from operator import ior\n&gt;&gt;&gt; l = [{'a': 1}, {'b': 2}, {'a': 100, 'c': 3}]\n&gt;&gt;&gt; reduce(ior, l, {})\n{'a': 100, 'b': 2, 'c': 3}\n</code></pre>\n<p>For Python 3.8 or less, the following can be used as an alternative to <code>ior</code>:</p>\n<pre><code>&gt;&gt;&gt; from functools import reduce\n&gt;&gt;&gt; l = [{'a': 1}, {'b': 2}, {'a': 100, 'c': 3}]\n&gt;&gt;&gt; reduce(lambda x, y: x.update(y) or x, l, {})\n{'a': 100, 'b': 2, 'c': 3}\n</code></pre>\n"}, {'answer_id': 50289800, 'author': 'Tigran Saluev', 'author_id': 999858, 'author_profile': 'https://Stackoverflow.com/users/999858', 'pm_score': 1, 'selected': False, 'text': "<p>I think my ugly one-liners are just necessary here.</p>\n<pre><code>z = next(z.update(y) or z for z in [x.copy()])\n# or\nz = (lambda z: z.update(y) or z)(x.copy())\n</code></pre>\n<ol>\n<li>Dicts are merged.</li>\n<li>Single expression.</li>\n<li>Don't ever dare to use it.</li>\n</ol>\n<p><strong>P.S.</strong> This is a solution working in both versions of Python. I know that Python 3 has this <code>{**x, **y}</code> thing and it is the right thing to use (as well as moving to Python 3 if you still have Python 2 is the right thing to do).</p>\n"}, {'answer_id': 54930992, 'author': 'ShadowRanger', 'author_id': 364696, 'author_profile': 'https://Stackoverflow.com/users/364696', 'pm_score': 4, 'selected': False, 'text': '<p>There will be a new option when Python 3.8 releases (<a href="https://www.python.org/dev/peps/pep-0569/#release-schedule" rel="noreferrer">scheduled for 20 October, 2019</a>), thanks to <a href="https://www.python.org/dev/peps/pep-0572/" rel="noreferrer">PEP 572: Assignment Expressions</a>. The new assignment expression operator <code>:=</code> allows you to assign the result of the <code>copy</code> and still use it to call <code>update</code>, leaving the combined code a single expression, rather than two statements, changing:</p>\n\n<pre><code>newdict = dict1.copy()\nnewdict.update(dict2)\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>(newdict := dict1.copy()).update(dict2)\n</code></pre>\n\n<p>while behaving identically in every way. If you must also return the resulting <code>dict</code> (you asked for an expression returning the <code>dict</code>; the above creates and assigns to <code>newdict</code>, but doesn\'t return it, so you couldn\'t use it to pass an argument to a function as is, a la <code>myfunc((newdict := dict1.copy()).update(dict2))</code>), then just add <code>or newdict</code> to the end (since <code>update</code> returns <code>None</code>, which is falsy, it will then evaluate and return <code>newdict</code> as the result of the expression):</p>\n\n<pre><code>(newdict := dict1.copy()).update(dict2) or newdict\n</code></pre>\n\n<p><strong>Important caveat:</strong> In general, I\'d discourage this approach in favor of:</p>\n\n<pre><code>newdict = {**dict1, **dict2}\n</code></pre>\n\n<p>The unpacking approach is clearer (to anyone who knows about generalized unpacking in the first place, <a href="https://www.python.org/dev/peps/pep-0448/" rel="noreferrer">which you should</a>), doesn\'t require a name for the result at all (so it\'s much more concise when constructing a temporary that is immediately passed to a function or included in a <code>list</code>/<code>tuple</code> literal or the like), and is almost certainly faster as well, being (on CPython) roughly equivalent to:</p>\n\n<pre><code>newdict = {}\nnewdict.update(dict1)\nnewdict.update(dict2)\n</code></pre>\n\n<p>but done at the C layer, using the concrete <code>dict</code> API, so no dynamic method lookup/binding or function call dispatch overhead is involved (where <code>(newdict := dict1.copy()).update(dict2)</code> is unavoidably identical to the original two-liner in behavior, performing the work in discrete steps, with dynamic lookup/binding/invocation of methods.</p>\n\n<p>It\'s also more extensible, as merging three <code>dict</code>s is obvious:</p>\n\n<pre><code> newdict = {**dict1, **dict2, **dict3}\n</code></pre>\n\n<p>where using assignment expressions won\'t scale like that; the closest you could get would be:</p>\n\n<pre><code> (newdict := dict1.copy()).update(dict2), newdict.update(dict3)\n</code></pre>\n\n<p>or without the temporary tuple of <code>None</code>s, but with truthiness testing of each <code>None</code> result:</p>\n\n<pre><code> (newdict := dict1.copy()).update(dict2) or newdict.update(dict3)\n</code></pre>\n\n<p>either of which is obviously much uglier, and includes further inefficiencies (either a wasted temporary <code>tuple</code> of <code>None</code>s for comma separation, or pointless truthiness testing of each <code>update</code>\'s <code>None</code> return for <code>or</code> separation).</p>\n\n<p><strong>The only real advantage to the assignment expression approach occurs if:</strong></p>\n\n<ol>\n<li><strong>You have generic code that needs handle both <code>set</code>s and <code>dict</code>s</strong> (both of them support <code>copy</code> and <code>update</code>, so the code works roughly as you\'d expect it to)</li>\n<li><strong>You expect to receive arbitrary dict-like objects</strong>, not just <code>dict</code> itself, <strong>and must preserve the type and semantics of the left hand side</strong> (rather than ending up with a plain <code>dict</code>). While <code>myspecialdict({**speciala, **specialb})</code> might work, it would involve an extra temporary <code>dict</code>, and if <code>myspecialdict</code> has features plain <code>dict</code> can\'t preserve (e.g. regular <code>dict</code>s now preserve order based on the first appearance of a key, and value based on the last appearance of a key; you might want one that preserves order based on the <em>last</em> appearance of a key so updating a value also moves it to the end), then the semantics would be wrong. Since the assignment expression version uses the named methods (which are presumably overloaded to behave appropriately), it never creates a <code>dict</code> at all (unless <code>dict1</code> was already a <code>dict</code>), preserving the original type (and original type\'s semantics), all while avoiding any temporaries.</li>\n</ol>\n'}, {'answer_id': 61116810, 'author': 'Roushan', 'author_id': 3462681, 'author_profile': 'https://Stackoverflow.com/users/3462681', 'pm_score': 3, 'selected': False, 'text': '<p><strong>Python 3.9+ only</strong></p>\n\n<p>Merge (|) and update (|=) operators have been added to the built-in <code>dict</code> class.</p>\n\n<pre><code>&gt;&gt;&gt; d = {\'spam\': 1, \'eggs\': 2, \'cheese\': 3}\n&gt;&gt;&gt; e = {\'cheese\': \'cheddar\', \'aardvark\': \'Ethel\'}\n&gt;&gt;&gt; d | e\n{\'spam\': 1, \'eggs\': 2, \'cheese\': \'cheddar\', \'aardvark\': \'Ethel\'}\n</code></pre>\n\n<p>The augmented assignment version operates in-place:</p>\n\n<pre><code>&gt;&gt;&gt; d |= e\n&gt;&gt;&gt; d\n{\'spam\': 1, \'eggs\': 2, \'cheese\': \'cheddar\', \'aardvark\': \'Ethel\'}\n</code></pre>\n\n<p>See <a href="https://www.python.org/dev/peps/pep-0584/" rel="noreferrer">PEP 584</a></p>\n'}, {'answer_id': 62141222, 'author': 'xjcl', 'author_id': 2111778, 'author_profile': 'https://Stackoverflow.com/users/2111778', 'pm_score': 4, 'selected': False, 'text': '<p><strong><a href="https://www.python.org/dev/peps/pep-0584/#specification" rel="noreferrer">New</a> in Python 3.9:</strong> Use the union operator (<code>|</code>) to merge <code>dict</code>s similar to <code>set</code>s:</p>\n<pre><code>&gt;&gt;&gt; d = {\'a\': 1, \'b\': 2}\n&gt;&gt;&gt; e = {\'a\': 9, \'c\': 3}\n&gt;&gt;&gt; d | e\n{\'a\': 9, \'b\': 2, \'c\': 3}\n</code></pre>\n<p>For matching keys, the <strong>right <code>dict</code> takes precedence</strong>.</p>\n<p>This also works for <code>|=</code> to modify a <code>dict</code> in-place:</p>\n<pre><code>&gt;&gt;&gt; e |= d    # e = e | d\n&gt;&gt;&gt; e\n{\'a\': 1, \'c\': 3, \'b\': 2}\n</code></pre>\n'}, {'answer_id': 62820532, 'author': 'Nico Schlömer', 'author_id': 353337, 'author_profile': 'https://Stackoverflow.com/users/353337', 'pm_score': 6, 'selected': False, 'text': '<p>I benchmarked the suggested with <a href="https://github.com/nschloe/perfplot" rel="noreferrer">perfplot</a> and found that the good old</p>\n<pre class="lang-py prettyprint-override"><code>x | y\n</code></pre>\n<p>is the fastest solution together with the good old</p>\n<pre><code>{**x, **y}\n</code></pre>\n<p>and</p>\n<pre><code>temp = x.copy()\ntemp.update(y)\n</code></pre>\n<p><a href="https://i.stack.imgur.com/TsI4P.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TsI4P.png" alt="enter image description here" /></a></p>\n<hr />\n<p>Code to reproduce the plot:</p>\n<pre class="lang-py prettyprint-override"><code>from collections import ChainMap\nfrom itertools import chain\nimport perfplot\n\n\ndef setup(n):\n    x = dict(zip(range(n), range(n)))\n    y = dict(zip(range(n, 2 * n), range(n, 2 * n)))\n    return x, y\n\n\ndef copy_update(x, y):\n    temp = x.copy()\n    temp.update(y)\n    return temp\n\n\ndef add_items(x, y):\n    return dict(list(x.items()) + list(y.items()))\n\n\ndef curly_star(x, y):\n    return {**x, **y}\n\n\ndef chain_map(x, y):\n    return dict(ChainMap({}, y, x))\n\n\ndef itertools_chain(x, y):\n    return dict(chain(x.items(), y.items()))\n\n\ndef python39_concat(x, y):\n    return x | y\n\n\nb = perfplot.bench(\n    setup=setup,\n    kernels=[\n        copy_update,\n        add_items,\n        curly_star,\n        chain_map,\n        itertools_chain,\n        python39_concat,\n    ],\n    labels=[\n        &quot;copy_update&quot;,\n        &quot;dict(list(x.items()) + list(y.items()))&quot;,\n        &quot;{**x, **y}&quot;,\n        &quot;chain_map&quot;,\n        &quot;itertools.chain&quot;,\n        &quot;x | y&quot;,\n    ],\n    n_range=[2 ** k for k in range(18)],\n    xlabel=&quot;len(x), len(y)&quot;,\n    equality_check=None,\n)\nb.save(&quot;out.png&quot;)\nb.show()\n</code></pre>\n'}, {'answer_id': 64228920, 'author': 'disooqi', 'author_id': 2377431, 'author_profile': 'https://Stackoverflow.com/users/2377431', 'pm_score': 3, 'selected': False, 'text': '<p><strong>In Python 3.9</strong></p>\n<p>Based on <a href="https://www.python.org/dev/peps/pep-0584/" rel="nofollow noreferrer">PEP 584</a>, the new version of Python introduces two new operators for dictionaries: union (|) and in-place union (|=). You can use | to merge two dictionaries, while |= will update a dictionary in place:</p>\n<pre><code>&gt;&gt;&gt; pycon = {2016: &quot;Portland&quot;, 2018: &quot;Cleveland&quot;}\n&gt;&gt;&gt; europython = {2017: &quot;Rimini&quot;, 2018: &quot;Edinburgh&quot;, 2019: &quot;Basel&quot;}\n\n&gt;&gt;&gt; pycon | europython\n{2016: \'Portland\', 2018: \'Edinburgh\', 2017: \'Rimini\', 2019: \'Basel\'}\n\n&gt;&gt;&gt; pycon |= europython\n&gt;&gt;&gt; pycon\n{2016: \'Portland\', 2018: \'Edinburgh\', 2017: \'Rimini\', 2019: \'Basel\'}\n\n</code></pre>\n<p>If d1 and d2 are two dictionaries, then <code>d1 | d2</code> does the same as <code>{**d1, **d2}</code>. The | operator is used for calculating the <a href="https://docs.python.org/3/library/stdtypes.html#frozenset.union" rel="nofollow noreferrer">union of sets</a>, so the notation may already be familiar to you.</p>\n<p>One advantage of using <code>|</code> is that it works on different dictionary-like types and keeps the type through the merge:</p>\n<pre><code>&gt;&gt;&gt; from collections import defaultdict\n&gt;&gt;&gt; europe = defaultdict(lambda: &quot;&quot;, {&quot;Norway&quot;: &quot;Oslo&quot;, &quot;Spain&quot;: &quot;Madrid&quot;})\n&gt;&gt;&gt; africa = defaultdict(lambda: &quot;&quot;, {&quot;Egypt&quot;: &quot;Cairo&quot;, &quot;Zimbabwe&quot;: &quot;Harare&quot;})\n\n&gt;&gt;&gt; europe | africa\ndefaultdict(&lt;function &lt;lambda&gt; at 0x7f0cb42a6700&gt;,\n  {\'Norway\': \'Oslo\', \'Spain\': \'Madrid\', \'Egypt\': \'Cairo\', \'Zimbabwe\': \'Harare\'})\n\n&gt;&gt;&gt; {**europe, **africa}\n{\'Norway\': \'Oslo\', \'Spain\': \'Madrid\', \'Egypt\': \'Cairo\', \'Zimbabwe\': \'Harare\'}\n</code></pre>\n<p>You can use a defaultdict when you want to effectively handle missing keys. Note that <code>|</code> preserves the defaultdict, while <code>{**europe, **africa}</code> does not.</p>\n<p>There are some similarities between how <code>|</code> works for dictionaries and how <code>+</code> works for lists. In fact, the <code>+</code> operator was <a href="https://www.python.org/dev/peps/pep-0584/#use-the-addition-operator" rel="nofollow noreferrer">originally proposed</a> to merge dictionaries as well. This correspondence becomes even more evident when you look at the in-place operator.</p>\n<p>The basic use of <code>|=</code> is to update a dictionary in place, similar to <code>.update()</code>:</p>\n<pre><code>&gt;&gt;&gt; libraries = {\n...     &quot;collections&quot;: &quot;Container datatypes&quot;,\n...     &quot;math&quot;: &quot;Mathematical functions&quot;,\n... }\n&gt;&gt;&gt; libraries |= {&quot;zoneinfo&quot;: &quot;IANA time zone support&quot;}\n&gt;&gt;&gt; libraries\n{\'collections\': \'Container datatypes\', \'math\': \'Mathematical functions\',\n \'zoneinfo\': \'IANA time zone support\'}\n</code></pre>\n<p>When you merge dictionaries with <code>|</code>, both dictionaries need to be of a proper dictionary type. On the other hand, the in-place operator (<code>|=</code>) is happy to work with any dictionary-like data structure:</p>\n<pre><code>&gt;&gt;&gt; libraries |= [(&quot;graphlib&quot;, &quot;Functionality for graph-like structures&quot;)]\n&gt;&gt;&gt; libraries\n{\'collections\': \'Container datatypes\', \'math\': \'Mathematical functions\',\n \'zoneinfo\': \'IANA time zone support\',\n \'graphlib\': \'Functionality for graph-like structures\'}\n</code></pre>\n'}, {'answer_id': 68883045, 'author': 'Brian', 'author_id': 8126390, 'author_profile': 'https://Stackoverflow.com/users/8126390', 'pm_score': 2, 'selected': False, 'text': "<p>A method is deep merging. Making use of the <code>|</code> operator in 3.9+ for the use case of dict <code>new</code> being a set of default settings, and dict <code>existing</code> being a set of existing settings in use. My goal was to merge in any added settings from <code>new</code> without over writing existing settings in <code>existing</code>. I believe this recursive implementation will allow one to upgrade a dict with new values from another dict.</p>\n<pre><code>def merge_dict_recursive(new: dict, existing: dict):\n    merged = new | existing\n\n    for k, v in merged.items():\n        if isinstance(v, dict):\n            if k not in existing:\n                # The key is not in existing dict at all, so add entire value\n                existing[k] = new[k]\n\n            merged[k] = merge_dict_recursive(new[k], existing[k])\n    return merged\n</code></pre>\n<p>Example test data:</p>\n<pre><code>new\n{'dashboard': True,\n 'depth': {'a': 1, 'b': 22222, 'c': {'d': {'e': 69}}},\n 'intro': 'this is the dashboard',\n 'newkey': False,\n 'show_closed_sessions': False,\n 'version': None,\n 'visible_sessions_limit': 9999}\nexisting\n{'dashboard': True,\n 'depth': {'a': 5},\n 'intro': 'this is the dashboard',\n 'newkey': True,\n 'show_closed_sessions': False,\n 'version': '2021-08-22 12:00:30.531038+00:00'}\nmerged\n{'dashboard': True,\n 'depth': {'a': 5, 'b': 22222, 'c': {'d': {'e': 69}}},\n 'intro': 'this is the dashboard',\n 'newkey': True,\n 'show_closed_sessions': False,\n 'version': '2021-08-22 12:00:30.531038+00:00',\n 'visible_sessions_limit': 9999}\n</code></pre>\n"}, {'answer_id': 69335330, 'author': 'worroc', 'author_id': 5871672, 'author_profile': 'https://Stackoverflow.com/users/5871672', 'pm_score': 2, 'selected': False, 'text': '<p>Deep merge of dicts:</p>\n<pre><code>from typing import List, Dict\nfrom copy import deepcopy\n\ndef merge_dicts(*from_dicts: List[Dict], no_copy: bool=False) -&gt; Dict :\n    &quot;&quot;&quot; no recursion deep merge of two dicts\n\n    By default creates fresh Dict and merges all to it.\n\n    no_copy = True, will merge all dicts to a fist one in a list without copy.\n    Why? Sometime I need to combine one dictionary from &quot;layers&quot;.\n    The &quot;layers&quot; are not in use and dropped immediately after merging.\n    &quot;&quot;&quot;\n\n    if no_copy:\n        xerox = lambda x:x\n    else:\n        xerox = deepcopy\n\n    result = xerox(from_dicts[0])\n\n    for _from in from_dicts[1:]:\n        merge_queue = [(result, _from)]\n        for _to, _from in merge_queue:\n            for k, v in _from.items():\n                if k in _to and isinstance(_to[k], dict) and isinstance(v, dict):\n                    # key collision add both are dicts.\n                    # add to merging queue\n                    merge_queue.append((_to[k], v))\n                    continue\n                _to[k] = xerox(v)\n\n    return result\n</code></pre>\n<p>Usage:</p>\n<pre><code>print(&quot;=============================&quot;)\nprint(&quot;merge all dicts to first one without copy.&quot;)\na0 = {&quot;a&quot;:{&quot;b&quot;:1}}\na1 = {&quot;a&quot;:{&quot;c&quot;:{&quot;d&quot;:4}}}\na2 = {&quot;a&quot;:{&quot;c&quot;:{&quot;f&quot;:5}, &quot;d&quot;: 6}}\nprint(f&quot;a0 id[{id(a0)}] value:{a0}&quot;)\nprint(f&quot;a1 id[{id(a1)}] value:{a1}&quot;)\nprint(f&quot;a2 id[{id(a2)}] value:{a2}&quot;)\nr = merge_dicts(a0, a1, a2, no_copy=True)\nprint(f&quot;r  id[{id(r)}] value:{r}&quot;)\n\nprint(&quot;=============================&quot;)\nprint(&quot;create fresh copy of all&quot;)\na0 = {&quot;a&quot;:{&quot;b&quot;:1}}\na1 = {&quot;a&quot;:{&quot;c&quot;:{&quot;d&quot;:4}}}\na2 = {&quot;a&quot;:{&quot;c&quot;:{&quot;f&quot;:5}, &quot;d&quot;: 6}}\nprint(f&quot;a0 id[{id(a0)}] value:{a0}&quot;)\nprint(f&quot;a1 id[{id(a1)}] value:{a1}&quot;)\nprint(f&quot;a2 id[{id(a2)}] value:{a2}&quot;)\nr = merge_dicts(a0, a1, a2)\nprint(f&quot;r  id[{id(r)}] value:{r}&quot;)\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/38987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3207/']