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

时间:2015-12-14 17:55:44

标签: python python-2.7 dictionary

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 in a:
--> False

9 个答案:

答案 0 :(得分:14)

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

答案 1 :(得分:7)

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.

答案 2 :(得分:3)

>>> 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

答案 3 :(得分:3)

将我的评论转换为答案:

使用已作为内置方法提供的dict.get方法(我假设它是最pythonic的)

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

根据文档 -

  

get(key,默认) -    如果key在字典中,则返回key的值,否则返回default。   如果未给出default,则默认为None,以便使用此方法   永远不会引发KeyError。

答案 4 :(得分:1)

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

答案 5 :(得分:0)

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.

答案 6 :(得分:0)

   a.get('a') == 1
=> True
   a.get('a') == 2
=> False

if None is valid item:

{'x': None}.get('x', object()) is None

答案 7 :(得分:0)

使用.get通常是检查密钥值对是否存在的最佳方法。

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

有一点需要注意,如果密钥存在但是是假的则会导致测试失败,这可能不是您想要的。请记住,这种情况很少发生。现在反向是一个更常见的问题。这是使用in来测试密钥的存在。我在阅读csv文件时经常发现这个问题。

实施例

# 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. 

答案 8 :(得分:0)

对于python 3.x 使用 if key in dict

参见示例代码

#!/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