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

后端 未结 9 921
無奈伤痛
無奈伤痛 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:26
       a.get('a') == 1
    => True
       a.get('a') == 2
    => False
    

    if None is valid item:

    {'x': None}.get('x', object()) is None
    
    0 讨论(0)
  • 2021-01-04 00:29

    You can check a tuple of the key, value against the dictionary's .items().

    test = {'a': 1, 'b': 2}
    print(('a', 1) in test.items())
    >>> True
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-04 00:34

    Converting my comment into an answer :

    Use the dict.get method which is already provided as an inbuilt method (and I assume is the most pythonic)

    >>> dict = {'Name': 'Anakin', 'Age': 27}
    >>> dict.get('Age')
    27
    >>> dict.get('Gender', 'None')
    'None'
    >>>
    

    As per the docs -

    get(key, default) - Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-04 00:35

    For python 3.x use if key in dict

    See the sample code

    #!/usr/bin/python
    a={'a':1,'b':2,'c':3}
    b={'a':1}
    c={'a':2}
    mylist = [a, b, c]
    for obj in mylist:
        if 'b' in obj:
            print(obj['b'])
    
    
    Output: 2
    
    0 讨论(0)
提交回复
热议问题