Python "extend" for a dictionary


Which is the best way to extend a dictionary with another one? For instance:

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

I'm looking for any operation to obtain this avoiding for loop:

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

I wish to do something like:

a.extend(b)  # This does not work
2/23/2009 11:18:49 AM

Accepted Answer

1/18/2019 6:41:12 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow