views:

3318

answers:

5

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
+25  A: 
a.update(b)

http://docs.python.org/library/stdtypes.html#mapping-types-dict

Nick Fortescue
+1: quote the docs
S.Lott
+5  A: 
a.update(b)

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

vartec
+2  A: 

I tried this statement but what I have is :

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

Did I do something wrong?

Taurus Olson
That's how it's supposed to work.Dictionaries in python does not store the elements in any special order.
gnud
+1  A: 

a python dictionary isn't sorted like a list is.

+2  A: 

A beautiful gem in this closed question:

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

basket = dict(basket_one, **basket_two)

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 hear 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

Tom Leys