首页 > 解决方案 > 查找python中两个dict之间的不匹配(键和值)

问题描述

查找两个字典之间的不匹配(键和值)

superset = {"a":1, "b": 2, "c": 3, "d":4}
subset = {"a":1, "b": 2, "c": 3, "d":4}
print(all(item in superset.items() for item in subset.items()))
# Expected output: True and desired output True


superset = {"a":1, "b": 2, "c": 3, "d":4, "e": 5}
subset = {"a":1, "b": 2, "c": 3, "d":5}
print(all(item in superset.items() for item in subset.items()))
# Expected output: False and desired output False

在测试用例下面,因为我只检查两个字典之间不匹配的键和值,所以在超集或子集字典中将忽略额外的键和值。在下面的情况下,子集中包含“e”是键,5 是对应的值,相同的键或值不存在于超集中,因此我们可以忽略,因为它不是不匹配的。

superset = {"a":1, "b": 2, "c": 3, "d":4}
subset = {"a":1, "b": 2, "c": 3, "d":4, "e": 5}
print(all(item in superset.items() for item in subset.items()))
# Expected output: True and desired output False

标签: pythonpython-3.x

解决方案


If you want to ignore mismatching keys, just check keys that exists in both dicts:

superset = {"a":1, "b": 2, "c": 3, "d":4, "f":8}
subset = {"a":1, "b": 2, "c": 3, "d":4, "e": 5}
print(
    all(
        superset[key] == subset[key] 
        for key in set(superset.keys()) & set(subset.keys())
    )
)

will print:

True


If you want to check that each dict contains no mismatched values from another, you should modify your code like this:

superset = {"a":1, "b": 2, "c": 3, "d":4, "f": 10, "g": 5}
subset = {"a":1, "b": 2, "c": 3, "d":4, "e": 5}
print(
    all(
        superset[key] == subset[key] 
        for key in set(superset.keys()) & set(subset.keys())
    ) and
    all(
        superset[key] not in subset.values()
        for key in set(superset.keys()) - set(subset.keys())
    ) and
    all(
        subset[key] not in superset.values()
        for key in set(subset.keys()) - set(superset.keys())
    )
)

will print:

False


推荐阅读