python:如何根据值合并字典列表中的字典 [英] python: how to merge dict in list of dicts based on value

查看:705
本文介绍了python:如何根据值合并字典列表中的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典列表,其中每个字典由3个键组成:名称,URL和位置.
在整个字典中,只有名称"的值可以相同,并且在整个列表中"URL"和位置"始终是不同的值.

I have a list of dicts, where each dict consists of 3 keys: name, url, and location.
Only value of 'name' can be the same throughout the dicts, and both 'url' and 'location' are always different value throughout the list.

示例:

[
{"name":"A1", "url":"B1", "location":"C1"}, 
{"name":"A1", "url":"B2", "location":"C2"}, 
{"name":"A2", "url":"B3", "location":"C3"},
{"name":"A2", "url":"B4", "location":"C4"}, ...
]  

然后我要根据名称"中的值对它们进行分组,如下所示.

Then I want to make them grouping based on the value in 'name' as follows.

预期:

[
{"name":"A1", "url":"B1, B2", "location":"C1, C2"},
{"name":"A2", "url":"B3, B4", "location":"C3, C4"},
]

(实际列表中包含2,000多个字典)

(actual list consists of >2,000 dicts)

我很高兴能解决这种情况.
任何建议/答案将不胜感激.

I'd be very glad to get solved this situation.
Any advice / answers will be greatly appreciated.

谢谢.

推荐答案

其中res是:

[{'location': 'C1', 'name': 'A1', 'url': 'B1'},
 {'location': 'C2', 'name': 'A1', 'url': 'B2'},
 {'location': 'C3', 'name': 'A2', 'url': 'B3'},
 {'location': 'C4', 'name': 'A2', 'url': 'B4'}]

您可以使用defaultdict处理数据并将结果解压缩为列表推导:

You can work with the data using a defaultdict and unpacking the result into a list comprehension:

from collections import defaultdict

result = defaultdict(lambda: defaultdict(list))

for items in res:
     result[items['name']]['location'].append(items['location'])
     result[items['name']]['url'].append(items['url'])

final = [
    {'name': name, **{inner_names: ' '.join(inner_values) for inner_names, inner_values in values.items()}}
    for name, values in result.items()
]

final是:

In [57]: final
Out[57]:
[{'location': 'C1 C2', 'name': 'A1', 'url': 'B1 B2'},
 {'location': 'C3 C4', 'name': 'A2', 'url': 'B3 B4'}]

这篇关于python:如何根据值合并字典列表中的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆