702

What is the best way to extend a dictionary with another one while avoiding the use of a for loop? For instance:

>>> a = { "a" : 1, "b" : 2 }
>>> b = { "c" : 3, "d" : 4 }
>>> a
{'a': 1, 'b': 2}
>>> b
{'c': 3, 'd': 4}

Result:

{ "a" : 1, "b" : 2, "c" : 3, "d" : 4 }

Something like:

a.extend(b)  # This does not work
2
  • 27
    I knew for lists [], then i supose may be work for others, not extrange ;-)
    – FerranB
    Commented Feb 23, 2009 at 13:05
  • 2
    This question is not uniquely defined as the example should cover the case where a and b have common keys
    – ntg
    Commented Jun 25, 2020 at 12:17

8 Answers 8

1019
a.update(b)

Latest Python Standard Library Documentation

5
  • 138
    keep in mind that update() directly modifies the dict and returns None.
    – e18r
    Commented Dec 5, 2015 at 23:15
  • 9
    But what if you only want to extend the dict with values that are not defined already (i.e. not overwriting existing values)? For instance, update a dict {"a":2, "b":3} with dict {"b":4, "c":5} to dict {"a":2, "b":3,"c":5}? Of course it's possible using update() by moving some stuff around, but it would be nicer if it could be accomplished in only one line...
    – Nearoo
    Commented Jan 6, 2016 at 16:28
  • 35
    @Nearoo - simply update the opposite way; instead of x.update(y) [which would overwrite x values with y], use y.update(x) [which overwrites y values with x] and use y as your chosen dict for further operations
    – jonathanl
    Commented Jan 27, 2016 at 2:20
  • 2
    keep in mind that update silently overwrites existing entries. Ie, any values in b overwrite those in a for overlapping keys. Commented Apr 1, 2020 at 11:43
  • 2
    @e18r Yes, please dont do a = a.update(b), this will turn a to None, a very common mistake. Commented May 30, 2023 at 12:07
264

A beautiful gem in this closed question:

The "oneliner way", altering neither of the input dicts, is

basket = dict(basket_one, **basket_two)

Learn what **basket_two (the **) means here.

In case of conflict, the items from basket_two will override the ones from basket_one. As one-liners go, this is pretty readable and transparent, and I have no compunction against using it any time a dict that's a mix of two others comes in handy (any reader who has trouble understanding it will in fact be very well served by the way this prompts him or her towards learning about dict and the ** form;-). So, for example, uses like:

x = mungesomedict(dict(adict, **anotherdict))

are reasonably frequent occurrences in my code.

Originally submitted by Alex Martelli

Note: In Python 3, this will only work if every key in basket_two is a string.

5
  • 6
    Documentation for dict is easy to find while ** is a bit more tricky (keyword is kwargs). Here is a nice explanation: saltycrane.com/blog/2008/01/…
    – johndodo
    Commented Mar 27, 2013 at 10:37
  • 4
    this may be used to generate a second variable with a single command, whereas basket_one.update(<dict>) as the name said, updates an existing dictionary (or a cloned one).
    – furins
    Commented Jan 17, 2014 at 16:08
  • 3
    Note that in Python 3, argument names, and thus the keys of **anotherdict, must be strings.
    – ᅠᅠᅠ
    Commented Aug 19, 2014 at 18:56
  • Thanks @johndodo - I've integrated your suggestions into the post.
    – Tom Leys
    Commented Jun 30, 2016 at 22:27
  • 1
    A nice functional alternative to the accepted answer. This approach is desirable if you need to directly use the newly combined dict. (also see @e18r's comment on the accepted answer). Commented Apr 8, 2019 at 19:47
108

Have you tried using dictionary comprehension with dictionary mapping:

a = {'a': 1, 'b': 2}
b = {'c': 3, 'd': 4}

c = {**a, **b}
# c = {"a": 1, "b": 2, "c": 3, "d": 4}

Another way of doing is by Using dict(iterable, **kwarg)

c = dict(a, **b)
# c = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

In Python 3.9 you can add two dict using union | operator

# use the merging operator |
c = a | b
# c = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
4
  • 6
    FYI : this is not a valid syntax in Python 2.7
    – Asav Patel
    Commented Apr 18, 2019 at 22:53
  • 4
    This syntax is fairly new (Python 3.5)
    – pianoJames
    Commented May 28, 2019 at 19:49
  • 1
    a.update(b) didn't work for me, and {**a, **b} did. Not sure why, but thanks for the alternative solution.
    – vtnate
    Commented Mar 2, 2021 at 15:42
  • @vtnate Probably because a.update(...) mutates the object a directly. It returns None afterwards. Commented May 19, 2023 at 13:34
32
a.update(b)

Will add keys and values from b to a, overwriting if there's already a value for a key.

25

Notice that since Python 3.9 a much easier syntax was introduced (Union Operators):

d1 = {'a': 1}
d2 = {'b': 2}

extended_dict = d1 | d2
>> {'a':1, 'b': 2}

Pay attention: in case first dict shared keys with second dict, position matters!

d1 = {'b': 1}
d2 = {'b': 2}
d1 | d2 
>> {'b': 2} 

Relevant PEP

23

As others have mentioned, a.update(b) for some dicts a and b will achieve the result you've asked for in your question. However, I want to point out that many times I have seen the extend method of mapping/set objects desire that in the syntax a.extend(b), a's values should NOT be overwritten by b's values. a.update(b) overwrites a's values, and so isn't a good choice for extend.

Note that some languages call this method defaults or inject, as it can be thought of as a way of injecting b's values (which might be a set of default values) in to a dictionary without overwriting values that might already exist.

Of course, you could simple note that a.extend(b) is nearly the same as b.update(a); a=b. To remove the assignment, you could do it thus:

def extend(a,b):
    """Create a new dictionary with a's properties extended by b,
    without overwriting.

    >>> extend({'a':1,'b':2},{'b':3,'c':4})
    {'a': 1, 'c': 4, 'b': 2}
    """
    return dict(b,**a)

Thanks to Tom Leys for that smart idea using a side-effect-less dict constructor for extend.

1
  • This was just what I was looking for. Very nice. Commented Jan 12, 2022 at 14:53
5

You can also use python's collections.ChainMap which was introduced in python 3.3.

from collections import ChainMap
c = ChainMap(a, b)
c['a'] # returns 1

This has a few possible advantages, depending on your use-case. They are explained in more detail here, but I'll give a brief overview:

  • A chainmap only uses views of the dictionaries, so no data is actually copied. This results in faster chaining (but slower lookup)
  • No keys are actually overwritten so, if necessary, you know whether the data comes from a or b.

This mainly makes it useful for things like configuration dictionaries.

2
  • Don't know if this has been renamed, but it is named "ChainMap" now and it is case sensitive if you're trying to import it.
    – Mat-KH
    Commented Dec 14, 2022 at 23:51
  • I don't think it was renamed, probably a typo on my part. Either way, it's updated now. Commented Dec 15, 2022 at 16:26
2

In terms of efficiency, it seems faster to use the unpack operation, compared with the update method.

Here an image of a test I did: enter image description here

Not the answer you're looking for? Browse other questions tagged or ask your own question.