2013-11-30 4 views
8

У меня есть список словарей в python. Теперь как объединить эти словари в единый объект в python. Пример словаряОбъединяющий список словаря в python

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

выход shouled быть:

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

На самом деле нет простого способа сделать это. –

ответ

14

Использование 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) 

выход:

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

гений. Я был в процессе этого. –

5
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()) 

Производит:

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

Или, используя наборы:

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()) 
3

В основном это небольшой вариант @ perreal Ответим (ответ, прежде чем был добавлен вариант defaultdict, я имею в виду!)

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()] 
0
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()] 
Смежные вопросы