python - 合并具有相同值的特定键的字典

标签 python

我有一组 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/

相关文章:

Python:捕获特定异常

python - 循环矩阵元素时出现索引错误

Python 将命令及其输出写入文件

python - 为什么 azure-sdk-for-python 返回对象

python - 如何在csv文件中写入一个文件,其中一列为字符串,另一列为字节

python - 对于嵌入式 Python,前缀 PYTHONPATH 不在 sys.path 中

python - 在 Python 中从字符串创建字典

python - 在django.shortcuts.render和django.views.generic.TemplateView之间选择

python - 脂肪 : can't figure out the architecture type of:/var/folders/

python - 从 Python 中的数组中删除列