检查字典中是否已经存在给定的键,并增加它 [英] Check if a given key already exists in a dictionary and increment it

查看:190
本文介绍了检查字典中是否已经存在给定的键,并增加它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个字典,我怎么知道该字典中的给定键是否已经设置为非无值?

Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?

我想这样做:

my_dict = {}

if (my_dict[key] != None):
  my_dict[key] = 1
else:
  my_dict[key] += 1

即,如果已经有一个,我想增加值,否则将其设置为1。

I.e., I want to increment the value if there's already one there, or set it to 1 otherwise.

推荐答案

p>您正在寻找 collections.defaultdict (适用于Python 2.5+)。这个

You are looking for collections.defaultdict (available for Python 2.5+). This

from collections import defaultdict

my_dict = defaultdict(int)
my_dict[key] += 1

将做你想要的。

对于常规Python dict ,如果给定键没有值,您将不会获取没有在访问dict时,会引发一个 KeyError 。所以如果你想使用一个常规的 dict ,而不是你的代码,你将使用

For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use

if key in my_dict:
    my_dict[key] += 1
else:
    my_dict[key] = 1

这篇关于检查字典中是否已经存在给定的键,并增加它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆