繁体   English   中英

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

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

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

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

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

使用的短路特性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

你已经标记了这个 2.7,而不是 2.x,所以你可以检查元组是否在 dict 的viewitems

(key, value) in d.viewitems()

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

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

您可以根据字典的.items()检查键、值的元组。

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

首先这是一种适用于 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

在 Python3 中,您还可以使用

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

对于 Python2,等价物是

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

将我的评论转换为答案:

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

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

根据文档 -

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

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

使用尝试/除外:

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

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

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

如果None是有效项目:

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

使用.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. 

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM