kishore
kishore

Reputation: 1748

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"]}]

Upvotes: 8

Views: 625

Answers (4)

DSM
DSM

Reputation: 353009

This is basically a slight variant of @perreal's answer (the answer before the defaultdict version was added, I mean!)

merged = {}
for d in input_dictionary:
    merged.setdefault(d["name"], set()).update(d["playing"])

output = [{"name": k, "playing": list(v)} for k,v in merged.items()]

Upvotes: 3

perreal
perreal

Reputation: 97928

toutput = {}
for entry in input_dictionary:
    if entry['name'] not in toutput: toutput[entry['name']] = []
    for p in entry['playing']:
        if p not in toutput[entry['name']]:
            toutput[entry['name']].append(p)
output = list({'name':n, 'playing':l} for n,l in toutput.items())

Produces:

[{'name': 'kishore', 'playing': ['cricket', 'basket ball', 'volley ball', 'hockey']}, {'name': 'xyz', 'playing': ['cricket']}]

Or, using sets:

from collections import defaultdict
toutput = defaultdict(set)
for entry in input_dictionary:
    toutput[entry['name']].update(entry['playing'])
output = list({'name':n, 'playing':list(l)} for n,l in toutput.items())

Upvotes: 5

Guy Gavriely
Guy Gavriely

Reputation: 11396

from collections import defaultdict
result = defaultdict(set)
[result[k[1]].update(v[1]) for k,v in [d.items() for d in input_dictionary]]
print [{'name':k, 'playing':v} for k,v in result.items()]

Upvotes: 0

falsetru
falsetru

Reputation: 368944

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'}]

Upvotes: 14

Related Questions