我有一个字典列表,其中每个字典包含 3 个键:名称、网址和位置。
只有 'name' 的值在整个字典中可以相同,而 'url' 和 'location' 在整个列表中始终是不同的值。
示例:
[
{"name":"A1", "url":"B1", "location":"C1"},
{"name":"A1", "url":"B2", "location":"C2"},
{"name":"A2", "url":"B3", "location":"C3"},
{"name":"A2", "url":"B4", "location":"C4"}, ...
]
然后我想让它们根据 'name' 中的值进行分组,如下所示。
预期:
[
{"name":"A1", "url":"B1, B2", "location":"C1, C2"},
{"name":"A2", "url":"B3, B4", "location":"C3, C4"},
]
(实际列表由 >2,000 个字典组成)
我很高兴能解决这个问题。
任何建议/答案将不胜感激。
提前致谢。
最佳答案
由于您的数据集相对较小,所以我想时间复杂度在这里不是什么大问题,因此您可以考虑使用以下代码。
from collections import defaultdict
given_data = [
{"name":"A1", "url":"B1", "location":"C1"},
{"name":"A1", "url":"B2", "location":"C2"},
{"name":"A2", "url":"B3", "location":"C3"},
{"name":"A2", "url":"B4", "location":"C4"},
]
D = defaultdict(list)
for item in given_data:
D[item['name']].append(item)
result = []
for x in D:
urls = ""
locations = ""
for pp in D[x]:
urls += pp['url']+" "
locations += pp['location']+" "
result.append({'name': x, 'url': urls.strip(), 'location': locations.strip()})
关于python:如何根据值合并dict列表中的dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50167565/