在Python中找到两个字典之间的不匹配(键和值)

时间:2019-05-14 15:13:42

标签: python python-3.x

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

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

3 个答案:

答案 0 :(得分:1)

如果您想忽略不匹配的键,只需检查两个字典中都存在的键:

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())
    )
)

将打印:

True


如果要检查每个字典是否包含彼此不匹配的值,则应按以下方式修改代码:

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())
    )
)

将打印:

False

答案 1 :(得分:0)

尝试一下:

superset = {"a":1, "b": 2, "c": 3, "d":4}
subset = {"a":1, "b": 2, "c": 3, "d":4}
print([*superset.items()] == [*subset.items()])

superset = {"a":1, "b": 2, "c": 3, "d":4, "e": 5}
subset = {"a":1, "b": 2, "c": 3, "d":5}
print([*superset.items()] == [*subset.items()])

superset = {"a":1, "b": 2, "c": 3, "d":4}
subset = {"a":1, "b": 2, "c": 3, "d":4, "e": 5}
print([*superset.items()] == [*subset.items()])

输出: enter image description here

这是第二个示例,其中每个字典具有相同的长度且具有相同的键,但是其中一个键具有与之相关的不同值,因此您知道它适用于键和值:

superset = {"a":1, "b": 2, "c": 3, "d":4, "e": 5}
subset = {"a":1, "b": 2, "c": 3, "d":5, "e":5}
print([*superset.items()],[*subset.items())
print([*superset.items()] == [*subset.items()])

输出: enter image description here

答案 2 :(得分:0)

您可以只循环一次,而不是像接受的答案一样循环几次。只需忽略不在超集中的键,并且由于我们正在对子集进行迭代,它将自动忽略超集中所有不在子集中的键。

print(all(subset[key] == superset[key] for key in subset if key in superset))

输出:

True
False
True