在增加现有值的同时向字典中添加新的键 [英] Add new keys to a dictionary while incrementing existing values
问题描述
第一种方式:
if x [3] in a:
a [x [3]] + = 1
else:
a [x [3 ]] = 1
第二种方式:
try:
b [x [3]] + = 1
除了KeyError:
b [x [3]] = 1
第三种方式:
从集合导入defaultdict
c = defaultdict(int)
c [x [3]] + = 1
我的问题是:哪种方式更有效率...更清洁...更好...等等还是有更好的方法。两种方式都可以作出相同的答案,但是我以为我会把蜂巢的头脑当作一个学习的例子。
谢谢 -
使用 collections.Counter
。 Counter
是 defaultdict(int)
的语法糖,但是很酷的是它在构造函数中接受一个迭代,因此节省了一个额外的步骤(我认为上面的所有示例都包含在for循环中。)
从集合导入计数器
count =计数器(x [3] for my_csv_reader中的x)
引入 collections.Counter
, collections.defaultdict
是此任务中最惯用的,因此对于用户< 2.7,使用 defaultdict
。
从集合import defaultdict
count = defaultdict(int)
for my_csv_reader中的x:
count [x [3]] + = 1
I am processing a CSV file and counting the unique values of column 4. So far I have coded this three ways. One uses "if key in dictionary", the second traps the KeyError and the third uses "DefaultDictionary". For example (where x[3] is the value from the file and "a" is a dictionary):
First way:
if x[3] in a:
a[x[3]] += 1
else:
a[x[3]] = 1
Second way:
try:
b[x[3]] += 1
except KeyError:
b[x[3]] = 1
Third way:
from collections import defaultdict
c = defaultdict(int)
c[x[3]] += 1
My question is: which way is more efficient... cleaner... better... etc. Or is there a better way. Both ways work and give the same answer, but I thought I would tap the hive mind as a learning case.
Thanks -
Use collections.Counter
. Counter
is syntactic sugar for defaultdict(int)
, but what's cool about it is that it accepts an iterable in the constructor, thus saving an extra step (I assume all of your examples above are wrapped in a for-loop.)
from collections import Counter
count = Counter(x[3] for x in my_csv_reader)
Prior to the introduction of collections.Counter
, collections.defaultdict
was the most idiomatic for this task, so for users < 2.7, use defaultdict
.
from collections import defaultdict
count = defaultdict(int)
for x in my_csv_reader:
count[x[3]] += 1
这篇关于在增加现有值的同时向字典中添加新的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!