如果我需要在右侧引用字典,如何将值分配给字典?

发布于 2025-02-09 20:44:15 字数 458 浏览 1 评论 0原文

这是给我一个键盘的代码。我知道为什么要这样做,但我对如何解决它很空白:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

还在原地等你 2025-02-16 20:44:15

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

defaultdict was designed for this.

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
丿*梦醉红颜 2025-02-16 20:44:15

如果您只想计算您山上的每个项目的发生,则需要collections.counter.counter

from collections import Counter


my_dict = Counter(range_val)

If you just want to count how many occurrences of each item are in your iterable, you want collections.Counter.

from collections import Counter


my_dict = Counter(range_val)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文