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

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

    Using get:

    # this doesn't work if `None` is a possible value
    # but you can use a different sentinal value in that case
    a.get('a') == 1
    

    Using try/except:

    # more verbose than using `get`, but more foolproof also
    a = {'a':1,'b':2,'c':3}
    try:
        has_item = a['a'] == 1
    except KeyError:
        has_item = False
    
    print(has_item)
    

    Other answers suggesting items in Python3 and viewitems in Python 2.7 are easier to read and more idiomatic, but the suggestions in this answer will work in both Python versions without any compatibility code and will still run in constant time. Pick your poison.

提交回复
热议问题