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"]}]
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'}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With