Created
September 21, 2011 21:05
-
-
Save rmax/1233315 to your computer and use it in GitHub Desktop.
using itertools's chain and groupby to merge a list of dictionaries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def merge_dicts(dict_list): | |
"""Merge all values from dict list into a single dict | |
>>> d1 = {'a': 1, 'b': 2} | |
>>> d2 = {'a': 2, 'b': 3} | |
>>> merge_dicts([d1, d2]) | |
{'a': [1, 2], 'b': [2, 3]} | |
""" | |
kviter = chain.from_iterable(d.iteritems() for d in dict_list) | |
grouped = groupby(sorted(kviter), itemgetter(0)) | |
return dict((k, [v for _, v in group]) for k, group in grouped) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment