【问题标题】:comparing keys:- list of nested dictionary比较键:- 嵌套字典列表
【发布时间】:2022-11-21 19:39:55
【问题描述】:

我想编写一个函数来检查 dict1(基本字典)的键并将其与 dict2(嵌套字典列表,可以是一个或多个)的键进行比较,以便它检查强制键,然后检查可选键(如果和无论存在什么)并将差异作为列表返回。

dict1 = {"name": str,                    #mandatory
        "details" : {                    #optional
            "class" : str,               #optional 
            "subjects" : {               #optional
                "english" : bool,        #optional
                "maths" : bool           #optional
            }
        }}

dict2 = [{"name": "SK",
        "details" : {
            "class" : "A"}
         },
         {"name": "SK",
        "details" : {
            "class" : "A",
            "subjects" :{
                "english" : True,
                "science" : False
            }
        }}]

将 dict2 与 dict1 进行比较后,预期输出为:-

pass          #no difference in keys in 1st dictionary
["science"]    #the different key in second dictionary of dict2

【问题讨论】:

    标签: python list dictionary nested comparison


    【解决方案1】:

    试试这个递归检查函数:

    def compare_dict_keys(d1, d2, diff: list):
        if isinstance(d2, dict):
            for key, expected_value in d2.items():
                try:
                    actual_value = d1[key]
                    compare_dict_keys(actual_value, expected_value, diff)
                except KeyError:
                    diff.append(key)
        else:
            pass
    

    字典 1 与字典 2

    difference = []
    compare_dict_keys(dict1, dict2, difference)
    print(difference)
    
    # Output: ['science']
    

    dict2 与 dict1

    difference = []
    compare_dict_keys(dict2, dict1, difference)
    print(difference)
    
    # Output: ['maths']
    

    【讨论】:

      【解决方案2】:

      转换成data frame并进行右反连接

      【讨论】:

      猜你喜欢
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 2021-05-10
      • 2019-07-07
      • 1970-01-01
      相关资源
      最近更新 更多