【问题标题】:How do I loop through nested dictionaries (from json) and check if key is in another nested dictionary (from json), and add if not?如何遍历嵌套字典(来自 json)并检查键是否在另一个嵌套字典中(来自 json),如果不是则添加?
【发布时间】:2021-07-29 19:25:57
【问题描述】:

我有两个嵌套字典(从 json 加载),需要检查一个中的键是否已经存在于另一个中,如果不存在,则添加它们。

示例 json:

eg_dict = {
    "A":
    {
        "A1":
        {
            "A1a": "bird",
            "A1b": true,
            "A1c": false
        },
        "A2":
        {
            "A2a":
            {
                "A2a1": "parrot",
                "A2a2":
                {
                    "enabled": true
                }
            }
        }
    },
    "B":
    {
        "B1":
        {
            "B1a": "Reptile"
        },
        "A2":
        {
            "A2a":
            {
                "A2a2":
                {
                    "enabled": true
                }
            }
        }
     }
}

我需要将 A1 和 A2a1 添加到 B。

我已经尝试过Check if a nested dictionary is a subset of another nested dictionary,但它并没有完全满足我的需求。

我开始尝试通过递归函数传递父键,但由于我不知道嵌套有多深,这似乎是一个死胡同?

def get_all_values(pkey, nested_dictionary):
#I don't think passing p(arent)key to the function gets me anywhere
    for key, value in nested_dictionary.items():
        if type(value) is dict:
            print(key, ":", value)
            get_all_values(pkey, value)
        else:
            print(key, ":", value)


def get_json(file, chartname):
    #print(chartname)
    with open(file) as file:
        file= json.load(file)
    b = file['B']
    #Can do it if I know the key I want to copy
    if 'A1' in file['A'].keys():
            b['A1'] = file['A']['A1']
    #Trying a function to get all missing keys from A
    get_all_values(key=None, file['B'])
    b = json.dumps(b)
    return b

第一次在stackoverflow上发帖,所以也欢迎帮助改进我的问题!

【问题讨论】:

  • 是否只添加 A 中 B 中缺少的那些键?或者还有那些在 A 中缺失但在 B 中的。
  • 请添加您想要的输出以澄清问题。

标签: python json


【解决方案1】:

AB 构建字典的递归解决方案,其中A 的值优先于B 的值:

a_dict = eg_dict['A']
b_dict = eg_dict['B']

print(a_dict)
# {'A1': {'A1a': 'bird', 'A1b': True, 'A1c': False}, 'A2': {'A2a': {'A2a1': 'parrot', 'A2a2': {'enabled': True}}}}
print(b_dict)
# {'B1': {'B1a': 'Reptile'}, 'A2': {'A2a': {'A2a2': {'enabled': True}}}}

def extend_dict(primary_dict, secondary_dict):
    result_dict = {}
    for k in set(primary_dict.keys()).union(set(secondary_dict.keys())):
        if (k in primary_dict.keys() and k in secondary_dict.keys()) and (isinstance(primary_dict[k], dict) and isinstance(secondary_dict[k], dict)):
            result_dict.update({k: extend_dict(primary_dict[k], secondary_dict[k])})
        elif k in primary_dict.keys():
            result_dict.update({k: primary_dict[k]})
        elif k in secondary_dict.keys():
            result_dict.update({k: secondary_dict[k]})
    return result_dict

extended = extend_dict(a_dict, b_dict) 
print(extended)
# {'B1': {'B1a': 'Reptile'}, 'A2': {'A2a': {'A2a2': {'enabled': True}, 'A2a1': 'parrot'}}, 'A1': {'A1a': 'bird', 'A1b': True, 'A1c': False}}

如果要切换优先级,只需切换AB,这样extended = extend_dict(b_dict, a_dict)即可。

如果这是您要找的,请告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-02
    • 2019-11-11
    • 1970-01-01
    • 2022-11-28
    • 2021-12-28
    • 2019-06-13
    • 2019-08-15
    • 2017-07-25
    相关资源
    最近更新 更多