python中字典的合并列表

2024-04-20 03:27:38 发布

您现在位置: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"]}]

输出应为:

^{pr2}$

Tags: name实体示例列表inputdictionary字典中将
3条回答

使用^{}

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)

输出:

^{pr2}$

这基本上是@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()]
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())

产生:

^{pr2}$

或者,使用集合:

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

相关问题 更多 >