如果我需要在右侧引用字典,如何将值分配给字典?
这是给我一个键盘的代码。我知道为什么要这样做,但我对如何解决它很空白:
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
我从阅读一堆文件和进行一些处理以获取所需的信息中获取数据。这些信息放在另一个词典上,然后我用来尝试这样做。也就是说,在示例中,我有range_val
,我有ymedict.values()
。
Here is the code that is giving me a KeyError. I understand why it's doing it but I am blank at how to solve it:
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
I get the data from reading a bunch of files and doing some processing to get the information I need. That information is held on another dictionary that I then use to try to do that. That is, instead of range_val
like in the example I have somedict.values()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DefaultDict
是为此设计的。defaultdict
was designed for this.如果您只想计算您山上的每个项目的发生,则需要
collections.counter.counter
。If you just want to count how many occurrences of each item are in your iterable, you want
collections.Counter
.