【问题标题】:python compare two nested dictionary keyspython比较两个嵌套的字典键
【发布时间】:2022-12-18 21:19:11
【问题描述】:

我只需要比较两个嵌套字典的键。 (主要用于外部 API 响应的实时测试以防止响应更改。) 例如,这两个字典匹配,但它们的值不同:

dict1 = {"guid": {
                "id": {
                    "addr": "fooo",
                    "creation_num": "4"
                }
            }
        }
dict2 = {"guid": {
                  "id": {
                      "addr": "bar",
                      "creation_num": "2"
                  }
                 }
        }

我尝试通过使用此方法重置字典的值来做到这一点

def recursive_dict_reset_values(dictionary, reset_value=0):
    for key, value in dictionary.items():
        if type(value) is dict:
            dictionary[key] = recursive_dict_reset_values(dictionary[key], reset_value)
        else:
            dictionary[key] = reset_value
    return dictionary

这种方法有效,但是有没有更pythonic和直接的方法?

【问题讨论】:

  • 两个 dict 对象的比较与更改 dict 中的非字典值有什么关系?

标签: python


【解决方案1】:

Python 不与嵌套字典进行比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多