在python中合并字典列表

在python中合并字典列表,第1张

在python中合并字典列表

使用

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5661966.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存