python3:判断b字典中是否包含a字典

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值