【发布时间】:2018-09-28 23:02:11
【问题描述】:
A = {
'a': 1,
'b': 2,
'c': 3
}
B = {
'a': 1,
'b': 2,
'c': 3,
'd': 4
}
我的目标是检查 A 是否是 B 的“子字典”。我的意思是 A 中的每一对 key:value 都在 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
有没有更好的方法来做到这一点?或者,也许是一种更 Pythonic 的方式,因为这看起来不像。
【问题讨论】:
标签: python python-3.x python-2.7 dictionary key