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

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

    Using .get is usually the best way to check if a key value pair exist.

    if my_dict.get('some_key'):
      # Do something
    

    There is one caveat, if the key exists but is falsy then it will fail the test which may not be what you want. Keep in mind this is rarely the case. Now the inverse is a more frequent problem. That is using in to test the presence of a key. I have found this problem frequently when reading csv files.

    Example

    # csv looks something like this:
    a,b
    1,1
    1,
    
    # now the code
    import csv
    with open('path/to/file', 'r') as fh:
      reader = csv.DictReader(fh) # reader is basically a list of dicts
      for row_d in reader:
        if 'b' in row_d:
          # On the second iteration of this loop, b maps to the empty string but
          # passes this condition statement, most of the time you won't want 
          # this. Using .get would be better for most things here. 
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-04 00:43

    You've tagged this 2.7, as opposed to 2.x, so you can check whether the tuple is in the dict's viewitems:

    (key, value) in d.viewitems()
    

    Under the hood, this basically does key in d and d[key] == value.

    In Python 3, viewitems is just items, but don't use items in Python 2! That'll build a list and do a linear search, taking O(n) time and space to do what should be a quick O(1) check.

    0 讨论(0)
提交回复
热议问题