检查给定的键是否已存在于字典中并将其递增 [英] Check if a given key already exists in a dictionary and increment it

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

问题描述

给定一个字典,我如何知道该字典中的给定键是否已设置为非 None 值?

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

也就是说,我想这样做:

I.e., I want to do this:

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.

推荐答案

您正在寻找 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 dicts,如果给定键没有值,则在访问 dict 时您将不会得到 None -- 将引发 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天全站免登陆