在Python中合并字典列表

8

我有一个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"]}]

输出应该是:
[{"name":"kishore", "playing":["cricket","basket ball","volley ball","hockey"]},{"name":"xyz","playing":["cricket"]}]
4个回答

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
天才。我正在制作这个过程中。 - Games Brainiac

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接