小编thi*_*ien的帖子

Python - 检查"subdictionary"

A = {
    'a': 1,
    'b': 2,
    'c': 3
}

B = {
    'a': 1,
    'b': 2,
    'c': 3,
    'd': 4
}
Run Code Online (Sandbox Code Playgroud)

我的目标是检查A是否是B的"子字典".我的意思是每一对键:A中的值都在B中.这是我的尝试

def is_sub_dict(first_dict, second_dict):
    for x in first_dict:
        if x not in second_dict or first_dict[x] != second_dict[x]:
            return False
    return True

is_sub_dict(A, B) #True
is_sub_dict(B, A) #False
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?或者,也许是一种更加pythonic的方式,因为这肯定不像它.

python dictionary key python-2.7 python-3.x

3
推荐指数
2
解决办法
148
查看次数

标签 统计

dictionary ×1

key ×1

python ×1

python-2.7 ×1

python-3.x ×1