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

编程入门 行业动态 更新时间:2024-10-19 08:55:40
本文介绍了检查给定的键是否已存在于字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:

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

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

I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?

推荐答案

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():

If you wanted a default, you can always use dict.get():

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

如果您想始终确保任何键的默认值,您可以使用 dict.setdefault() 重复或 defaultdict 来自 collections 模块,像这样:

and if you wanted to always ensure a default value for any key you can either use dict.setdefault() repeatedly or defaultdict from the collections module, like so:

from collections import defaultdict d = defaultdict(int) for i in range(100): d[i % 10] += 1

但总的来说,in 关键字是最好的方法.

but in general, the in keyword is the best way to do it.

更多推荐

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

本文发布于:2023-11-06 14:09:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563906.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!