Merging Dictionaries and Lists in Python

February 5, 2008

Edit:

Apparently this got posted to reddit a while ago, and several better versions were provided, here's what I would use now:

[code] def merge_lists(*ls): return sum(ls, []) def merge_dicts(*dicts): dict(merge_lists(*map(dict.items, dicts))) [/code]


I came up with what I think is a rather pretty and elegant way to merge dictionaries (and lists) in Python:

[code]def merge_lists(*lists): return reduce(lambda x, y: x+y,lists) def merge_dicts(*dictionaries): result = {} for key in set(merge_lists([d.keys() for d in dictionaries])): result[key] = merge_lists([d[key] for d in dictionaries if key in d]) return result [/code]

Some explanation for novices:

Merging Dictionaries and Lists in Python - February 5, 2008 - Michael Katsevman