是否可以检查Python字典中的动态路径?

问题描述 投票:0回答:1

我想知道是否可以动态循环字典中的路径并打印不匹配的值?

我有两个字典,有很多字段....

字典1

{
    "key": "3000",
    "fields": {
        "customfield_14550": null,
        "customfield_12770": null,
        "customfield_11441": "2023-07-13T12:45:00.000+0200",
        "customfield_12772": null,
        "customfield_14444": null,
        "customfield_10120": null,
        "customfield_12941": null,
        "customfield_14445": null,
        "customfield_12940": null,
        "customfield_14446": null,
        "due_date": null
    }
}

字典2

{
    "key": "3105",
    "fields": {
        "customfield_14550": null,
        "customfield_12770": null,
        "customfield_11441": "2023-07-13T12:45:00.000+0200",
        "customfield_12772": null,
        "customfield_14444": "different",
        "customfield_10120": null,
        "customfield_12941": "different",
        "customfield_14445": null,
        "customfield_12940": null,
        "customfield_14446": null,
        "due_date": null
    }
}

我有这个小脚本,应该检查两者之间所有不同的键。

keys = {
     # path and description
    ("fields.customfield_14550", "name-1"),
    ("fields.customfield_12770", "name-2"),
    ("fields.customfield_11441", "name-3"),
    ("fields.customfield_12772", "name-4"),
    ("fields.customfield_14444", "name-5"),
    ("fields.customfield_10120", "name-6"),
    ("fields.customfield_12941", "name-7"),
    ("fields.customfield_14445", "name-8"),
    ("fields.customfield_12940", "name-9"),
    ("fields.customfield_14446", "name-10"),
    ("fields.due_date", "date")
}

for key in keys:
    path, description = key
    if dict1.get(path) != dict2.get(path):
        print('---')
        print(description, path)
        print('---')

        print('--->')
        print(dict1.get(path))
        print(dict2.get(path))
        print('--->')

但是,当我在字典上使用 get() 方法时,我似乎无法从中获取值。只是一个错误......

AttributeError: 'tuple' object has no attribute 'get'

这是为什么?

python dictionary compare
1个回答
0
投票

get()
方法只能用于字典,不能用于元组。

在循环中,

key
是一个包含路径和描述的元组,因此您需要使用这些路径分别访问字典
dict1
dict2
来获取它们的值:

for path, description in keys:
    value1 = dict1["fields"].get(path)
    value2 = dict2["fields"].get(path)

    if value1 != value2:
        print('---')
        print(description, path)
        print('---')

        print('--->')
        print(value1)
        print(value2)
        print('--->')
© www.soinside.com 2019 - 2024. All rights reserved.