1.set函数,如果是两个不可变,且不存在字典嵌套的情况下,可以使用set函数:
简短的字典:
如果存在字典嵌套则会报错:
使用set源码:
# 判断字典a中是否包含字典b
def is_include_dic(dic1, dic2):
a = set(dic1.items())
b = set(dic2.items())
res = a.issubset(b)
return res
d1 = {"a": 3}
d2 = {"a": 3, "b": 2}
r = is_include_dic(d1, d2)
print(r)
2.自定义方法,如果包含,则返回true,否则返回false:
def dic_a_in_b(dic1, dic2):
res = None
for key in dic1:
print(key)
if (key in dic1) and (dic1[key] == dic2[key]):
res = True
else:
res = False
return res
d1 = {"a": {"t": 3}}
d2 = {"t": 2, "a": {"t": 3}}
r = dic_a_in_b(d1, d2)
print(r)