Here's a one-liner (imports
don't count :) that can easily be generalized to concatenate N dictionaries:
Python 3
from itertools import chain
dict(chain.from_iterable(d.items() for d in (d1, d2, d3)))
and:
from itertools import chain
def dict_union(*args):
return dict(chain.from_iterable(d.items() for d in args))
Python 2.6 & 2.7
from itertools import chain
dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3))
Output:
>>> from itertools import chain
>>> d1={1:2,3:4}
>>> d2={5:6,7:9}
>>> d3={10:8,13:22}
>>> dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3)))
{1: 2, 3: 4, 5: 6, 7: 9, 10: 8, 13: 22}
Generalized to concatenate N dicts:
from itertools import chain
def dict_union(*args):
return dict(chain.from_iterable(d.iteritems() for d in args))
I'm a little late to this party, I know, but I hope this helps someone.