如何添加或增加字典条目? [英] How to add or increment a dictionary entry?

查看:36
本文介绍了如何添加或增加字典条目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在长时间缺席并喜欢 Python 后重新接触 Python.然而,我发现自己一次又一次地遇到了一个模式.我一直在想,一定有更好的方式来表达我想要的东西,而且我可能做错了.

I'm currently re-engaging with Python after a long absence and loving it. However, I find myself coming across a pattern over and over. I keep thinking that there must be a better way to express what I want and that I'm probably doing it the wrong way.

我正在编写的代码格式如下:

The code that I'm writing is in the following form:

# foo is a dictionary
if foo.has_key(bar):
  foo[bar] += 1
else:
  foo[bar] = 1

我在我的程序中写了很多.我的第一反应是将它推送到一个辅助函数,但 Python 库通常已经提供了这样的东西.

I'm writing this a lot in my programs. My first reaction is to push it out to a helper function, but so often the python libraries supply things like this already.

有没有我遗漏的一些简单的小语法技巧?或者这是应该的方式吗?

Is there some simple little syntax trick that I'm missing? Or is this the way that it should be done?

推荐答案

Use a defaultdict:

from collections import defaultdict

foo = defaultdict(int)
foo[bar] += 1

在 Python >= 2.7 中,您还有一个单独的 计数器 类用于这些目的.对于 Python 2.5 和 2.6,您可以使用其反向移植版本.

In Python >= 2.7, you also have a separate Counter class for these purposes. For Python 2.5 and 2.6, you can use its backported version.

这篇关于如何添加或增加字典条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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