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:
- The
*argnotation means that any unnamed arguments (that is, not like this:funct(foo="bar")) will be stores in a tuple named arg. - The
reduce(funct,collection)will sequentially apply the functionfunct()to each member ofcollection. The classic example is thatreduce(lambda x, y: x+y, [1, 2, 3, 4, 5])calculates((((1+2)+3)+4)+5). - List comperehensions are super fun and work like this:
[something(value) for value in list]doessomethingto eachvalueinlist, and returns the results in a list containing the results ofsomething(value). There is a permutation that looks like this:[something(value) for value in list if value > 5](any condition can be placed after theif), this only addssomething(value)to the list if the condition istrue.