python - 检查给定键是否已存在于字典中

标签 python dictionary

我想在更新键的值之前测试一个键是否存在于字典中。 我写了以下代码:

if 'key1' in dict.keys():
  print "blah"
else:
  print "boo"

我认为这不是完成这项任务的最佳方式。有没有更好的方法来测试字典中的键?

最佳答案

in测试 dict 中的键是否存在:

d = {"key1": 10, "key2": 23}

if "key1" in d:
    print("this will execute")

if "nonexistent key" in d:
    print("this will not")

使用 dict.get()在键不存在时提供默认值:

d = {}

for i in range(10):
    d[i] = d.get(i, 0) + 1

要为 每个 键提供默认值,请使用 dict.setdefault()每个作业:

d = {}

for i in range(10):
    d[i] = d.setdefault(i, 0) + 1

或使用 defaultdict来自 collections模块:

from collections import defaultdict

d = defaultdict(int)

for i in range(10):
    d[i] += 1

关于python - 检查给定键是否已存在于字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1602934/

相关文章:

python - Pandas : how do I create a column based on data from the same dataframe?

java - 寻找开发互斥锁的解决方案

python - 在 SLD 中添加一个新的过滤器

javascript - Google App Engine,使用 Jquery 和 Python 提供文件,返回 2 个相同的文件而不是 1 个

python - 如何用正则表达式同时搜索两个可能的引号?

python - 将常量整数添加到 python 字典中的值

python - 嵌套Python字典

python - 随机 "int is not subscriptable"行为

java - 将范围(最小-最大)映射到单个值,如果某个值在某个范围内,则返回在 java 中映射的值

php - PHP下如何调用python脚本文件?