Python检查字典是否是其他字典的一部分

标签 python dictionary compare

我有 2 个具有相同键的字典

dict1 = {'version': 222,'name_app': 'foo1'}
dict2 = {'version': 222,'name_app': 'foo1','dir': 'c','path': 'cc'}

现在我想检查 dict1 是否具有与 dict2 相同的键和值 我喜欢避免循环并检查 dict1 中的每个键和值是否在 dict 2 中 有什么 pythonic 优雅的方法可以做到这一点吗?
更新
dict1 的两个键大多数都在 dict 2 中,如果只有 1 个匹配它是 false

最佳答案

你可以这样做

set(dict1.items())-set(dict2.items())== set()

它会根据你的条件返回true或false

如果字典有列表:

from operator import *
g = itemgetter(*dict1)
print(dict1.keys() <= dict2.keys() and g(dict1) == g(dict2))

关于Python检查字典是否是其他字典的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68246313/

相关文章:

python - 在 Python 中使用 Beautiful Soup 在线检查产品的可用性

javascript - 使用柏林噪声制作 map ?

python - 将包含浮点值的字典写入文件: TypeError: 'float' object is not iterable

java - 哈希集中的重复元素(正确实现比较器/比较方法后)

python - 使用 BERT 模型进行推理时没有batch_size

python - Python 中 scipy.integrate 的 odeint 给出了错误的结果?

vba - Excel VBA 字典 : add matching criteria if the data doesn't match with dictionary

c++ - 使用 std::string.compare() 不起作用

java - XMLunit 比较失败,因为子节点顺序

python - 有没有办法在Python中自动刷新/fsync stderr?