gpt4 book ai didi

python - 在python中合并字典列表

转载 作者:太空狗 更新时间:2023-10-29 20:36:37 25 4
gpt4 key购买 nike

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

输出应该是:

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

最佳答案

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

关于python - 在python中合并字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20297175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com