如何检查字典中是否存在键值对? [英] How to check if a key-value pair is present in a dictionary?

查看:97
本文介绍了如何检查字典中是否存在键值对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种聪明的pythonic方法来检查字典中是否有项目(键,值)?

Is there a smart pythonic way to check if there is an item (key,value) in a dict?

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

b in a:
--> True
c in a:
--> False

推荐答案

使用and的短路属性.这样,如果左手为假,则在检查该值时将不会得到KeyError.

Use the short circuiting property of and. In this way if the left hand is false, then you will not get a KeyError while checking for the value.

>>> a={'a':1,'b':2,'c':3}
>>> key,value = 'c',3                # Key and value present
>>> key in a and value == a[key]
True
>>> key,value = 'b',3                # value absent
>>> key in a and value == a[key]
False
>>> key,value = 'z',3                # Key absent
>>> key in a and value == a[key]
False

这篇关于如何检查字典中是否存在键值对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆