我有一组 2 种模式的字典,如 {"Id": 1, "title":"example"}
和 {"Id": 1, "location": “城市”
。我想将这两个组合在一起以获得 {"Id": 1, "title":"example", "location":"city"}
,对于所有具有 Id< 的词典
匹配。在这种情况下,该组包含 200 个项目,包括 100 个 title
和 100 个 location
,所有项目的 Id
都在 0-99 之间。我想返回一个包含 100 个组合词典的列表。
可能像下面这样:
def ResultHandler(extractedResult: list):
jsonObj = {}
jsonList = []
for result in extractedResult:
for key, val in result.items():
#this works if its hardcoded val to a number...
if key == "Id" and val == 1:
jsonObj.update(result)
jsonList.append(jsonObj)
return jsonList
最佳答案
按 ID 对字典进行分组。然后合并每个组。
from collections import defaultdict
def merge_dicts(dicts):
grouped = defaultdict(list)
for d in dicts:
grouped[d['id']].append(d)
merged = []
for ds in grouped.values():
m = {}
for d in ds:
m |= d # If Python < 3.9 : m = {**m, **d}
merged.append(m)
return merged
关于python - 合并具有相同值的特定键的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71282245/