How to check if a key-value pair is present in a dictionary?

后端 未结 9 926
無奈伤痛
無奈伤痛 2021-01-03 23:50

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          


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-04 00:31

    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
    

提交回复
热议问题