Website Logo. Upload to /source/logo.png ; disable in /source/_includes/logo.html

Mocking Eye

'Tis all in vain?

Merging Dictionaries and Lists in Python

| Comments


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 *arg notation 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 function funct() to each member of collection. The classic example is that reduce(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] does something to each value in list, and returns the results in a list containing the results of something(value). There is a permutation that looks like this: [something(value) for value in list if value > 5] (any condition can be placed after the if), this only adds something(value) to the list if the condition is true.