Tuesday, September 27, 2005

Combining Dictionaries in Python

On #python (of fslc.usu.edu's IRC server) today rjr and pauly mentioned different ways to combine dictionaries in Python. Pauly had a function that did the following:

def dictadd(somedicts):
    return dict([item for d in somedicts for item in d.iteritems()])

rjr mentioned he saw the following on the Python Cookbook:

def adddict(dict1, dict2):
    return dict(dict1, **dict2)

This seems to work fine with Python 2.4. Apparently this used to only work with string keys for the dictionaries. Now both approaches seem to work fine:

>>> baz = {'a': 'b', 'c': 'd', 'e': 'f'}
>>> bar = dict({'1' : 2}, **{lambda x: x : 'n' })
>>> bacena
{'a': 'b', '1': 2, 'c': 'd', 'e': 'f', <function <lambda> at 0xb7df5e64>: 'n'}

>>> ham = adddict(baz, bar)
>>> ham
{'a': 'b', '1': 2, 'c': 'd', 'e': 'f', <function <lambda> at 0xb7df4e64>: 'n'}

No comments:

Post a Comment