Python检查字典中是否定义了键

26 浏览
0 Comments

Python检查字典中是否定义了键

这个问题已经有答案了

在Python中检查是否已存在指定的字典键

如何检查一个键是否已经定义在Python字典中?

a={}
...
if 'a contains key b':
  a[b] = a[b]+1
else
  a[b]=1

admin 更改状态以发布 2023年5月20日
0
0 Comments

它的语法是if key in dict:

if "b" in a:
    a["b"] += 1
else:
    a["b"] = 1

现在您可能想查看collections.defaultdict和(对于上述情况)collections.Counter

0
0 Comments

使用 in 操作符:

if b in a:

示例:

>>> a = {'foo': 1, 'bar': 2}
>>> 'foo' in a
True
>>> 'spam' in a
False

你真的想要开始阅读 Python 教程,关于字典的章节特别介绍了这个主题。

0