简体   繁体   English

如何遍历嵌套字典(来自 json)并检查键是否在另一个嵌套字典(来自 json)中,如果不是则添加?

[英]How do I loop through nested dictionaries (from json) and check if key is in another nested dictionary (from json), and add if not?

I have two nested dictionaries (loaded from json) and need to check if the keys in one already exist in the other, and if not add them.我有两个嵌套字典(从 json 加载),需要检查一个中的键是否已经存在于另一个中,如果不存在,则添加它们。

Example 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
                }
            }
        }
     }
}

I need to add A1 and A2a1 to B.我需要将 A1 和 A2a1 添加到 B。

I've tried Check if a nested dictionary is a subset of another nested dictionary but it's not doing quite what I need.我试过检查嵌套字典是否是另一个嵌套字典的子集,但它并没有完全满足我的需要。

I started trying to pass the parent key through a recursive function, but as I don't know how deep the nesting goes, this seems like a dead end?我开始尝试通过递归函数传递父键,但由于我不知道嵌套有多深,这似乎是一个死胡同?

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

First time posting on stackoverflow, so help on improving my question welcome too!第一次在 stackoverflow 上发帖,所以也欢迎帮助改进我的问题!

A recursive solution to build a dictionary from A and B , where values of A have precedence over values of B :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}}

If you want to switch the precedence, just switch A and B , such that extended = extend_dict(b_dict, a_dict) .如果你想切换优先级,只需切换AB ,这样extended = extend_dict(b_dict, a_dict)

Let me know if this is what you are looking for.如果这就是您要找的,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM