如果我需要在右手边引用它,如何分配值给字典?



这是给我一个KeyError的代码。我明白它为什么这样做,但我不知道如何解决它:

mydict = {}
range_val = [str(i).zfill(2) for i in range(100)]
for v in range_val:
mydict[v] = mydict[v] + 1  # Should create key if doesnt exist yet and value be 1
# Should update key if already exists and update value to +1

我通过读取一堆文件和做一些处理来获得我需要的信息来获得数据。这些信息保存在另一个字典中,然后我用它来尝试这样做。也就是说,我用somedict.values()代替例子中的range_val

defaultdict就是为此而设计的。

import collections
mydict = collections.defaultdict(int)
range_val = [str(i).zfill(2) for i in range(100)]
for v in range_val:
mydict[v] = mydict[v] + 1

如果您只想计算每个项在iterable中出现的次数,则需要collections.Counter

from collections import Counter

my_dict = Counter(range_val)

最新更新