Python 如何检查字典中是否存在键值对?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34273544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:43:39  来源:igfitidea点击:

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

pythonpython-2.7dictionary

提问by Peter

Is there a smart pythonic way to check if there is an item (key,value) in a dict?

有没有一种智能的pythonic方法来检查字典中是否有一个项目(键,值)?

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

b in a:
--> True
c in a:
--> False

采纳答案by Bhargav Rao

Use the short circuiting property of and. In this way if the left hand is false, then you will not get a KeyErrorwhile checking for the value.

使用 的短路特性and。这样如果左手是假的,那么你就不会得到一段KeyError时间检查值。

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

回答by Morgan Thrapp

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

您可以根据字典的.items().

test = {'a': 1, 'b': 2}
print(('a', 1) in test.items())
>>> True

回答by user2357112 supports Monica

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

您已经标记了这个 2.7,而不是 2.x,因此您可以检查元组是否在 dict 中viewitems

(key, value) in d.viewitems()

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

在幕后,这基本上做到了key in d and d[key] == value

In Python 3, viewitemsis just items, but don't use itemsin 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.

在 Python 3 中,viewitems只是items,但不要items在 Python 2 中使用!这将构建一个列表并进行线性搜索,花费 O(n) 时间和空间来执行应该是快速 O(1) 检查的操作。

回答by John La Rooy

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

First here is a way that works for Python2 andPython3

首先这是一种适用于 Python2Python3 的方法

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

在 Python3 中,您还可以使用

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

For Python2, the equivalent is

对于 Python2,等价物是

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

回答by eestrada

Using get:

使用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 itemsin Python3 and viewitemsin 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.

items在 Python3 和viewitemsPython 2.7 中建议的其他答案更易于阅读且更惯用,但此答案中的建议将适用于没有任何兼容性代码的两个 Python 版本,并且仍将在恒定时间内运行。选择你的毒药。

回答by GingerPlusPlus

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

if Noneis valid item:

如果None是有效项目:

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

回答by letsc

Converting my comment into an answer :

将我的评论转换为答案:

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

使用dict.get已经作为内置方法提供的方法(我认为是最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.

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

回答by Dan

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

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

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 into test the presence of a key. I have found this problem frequently when reading csv files.

有一个警告,如果密钥存在但为假,那么它将无法通过测试,这可能不是您想要的。请记住,这种情况很少发生。现在逆是一个更常见的问题。那是in用来测试密钥的存在。我在阅读 csv 文件时经常发现这个问题。

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. 

回答by IRSHAD

For python 3.x use if key in dict

对于 python 3.x 使用 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