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

后端 未结 9 1020
無奈伤痛
無奈伤痛 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:39

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

    First here is a way that works for Python2 and Python3

    >>> all(k in a and a[k] == b[k] for k in b)
    True
    >>> all(k in a and a[k] == c[k] for k in c)
    False
    

    In Python3 you can also use

    >>> b.items() <= a.items()
    True
    >>> c.items() <= a.items()
    False
    

    For Python2, the equivalent is

    >>> b.viewitems() <= a.viewitems()
    True
    >>> c.viewitems() <= a.viewitems()
    False
    

提交回复
热议问题