Python "extend" for a dictionary

FerranB picture FerranB · Feb 23, 2009 · Viewed 265.5k times · Source

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