Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging list of dictionary in python

I have a list of dictionaries in python. Now how do i merge these dictionaries into single entity in python. Example dictionary is

input_dictionary = [{"name":"kishore", "playing":["cricket","basket ball"]},
                    {"name":"kishore", "playing":["volley ball","cricket"]},
                    {"name":"kishore", "playing":["cricket","hockey"]},
                    {"name":"kishore", "playing":["volley ball"]},
                    {"name":"xyz","playing":["cricket"]}]

output shouled be:

[{"name":"kishore", "playing":["cricket","basket ball","volley ball","hockey"]},{"name":"xyz","playing":["cricket"]}]
like image 775
kishore Avatar asked Nov 30 '13 06:11

kishore


1 Answers

Using itertools.groupby:

input_dictionary = [{"name":"kishore", "playing":["cricket","basket ball"]},
                    {"name":"kishore", "playing":["volley ball","cricket"]},
                    {"name":"kishore", "playing":["cricket","hockey"]},
                    {"name":"kishore", "playing":["volley ball"]},
                    {"name":"xyz","playing":["cricket"]}]
import itertools
import operator

by_name = operator.itemgetter('name')
result = []
for name, grp in itertools.groupby(sorted(input_dictionary, key=by_name), key=by_name):
    playing = set(itertools.chain.from_iterable(x['playing'] for x in grp))
    # If order of `playing` is important use `collections.OrderedDict`
    # playing = collections.OrderedDict.fromkeys(itertools.chain.from_iterable(x['playing'] for x in grp))
    result.append({'name': name, 'playing': list(playing)})

print(result)

output:

[{'playing': ['volley ball', 'basket ball', 'hockey', 'cricket'], 'name': 'kishore'}, {'playing': ['cricket'], 'name': 'xyz'}]
like image 123
falsetru Avatar answered Sep 21 '22 13:09

falsetru