关于Python字典中键值自增的问题

发布于 2025-01-15 16:37:26 字数 743 浏览 2 评论 0原文

我是 python 新手,有一个关于增加字典中键值的问题!我通过谷歌搜索并找到了解决方案 - 例如 get() 或 defaultdict()。但是,我仍然不明白其背后的逻辑。如果您能向我解释,我将非常感谢您的帮助,谢谢!!

所以我的原始代码是这样的:

list = ['a', 'b', 'c', 'd', 'e']
my_dict = {}
for item in list:
    my_dict[item] += 1
print(my_dict)

此代码抛出一个键错误,我理解这是因为不存在的键值。 这是我尝试的解决方案:

list = ['a', 'b', 'c', 'd', 'e']

mydict = {}
for item in list:
    if item not in mydict.keys():
        mydict[item] = 1
    else:
        mydict[item] += 1
print(mydict)

但是,输出并没有真正增加值并给了我这个:

{'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1}

我认为当它循环遍历列表中的每个项目时,它应该每次检查“if”语句,所以我很困惑为什么它没有发生在这里。

您知道是否可以在不使用我上面提到的任何函数/方法的情况下完成这项工作吗?太感谢了!

最好的, 园

I'm new to python and have a question about incrementing key values in dictionary! I was able to google around and found the solutions - like get() or defaultdict(). however, I still don't understand the logic behind it. Would really appreciate your help if you can explain to me, thanks!!

So my original code is this:

list = ['a', 'b', 'c', 'd', 'e']
my_dict = {}
for item in list:
    my_dict[item] += 1
print(my_dict)

This code throws a keyerror, I understand it's because of the non-existent key value.
Here's a solution I attempted:

list = ['a', 'b', 'c', 'd', 'e']

mydict = {}
for item in list:
    if item not in mydict.keys():
        mydict[item] = 1
    else:
        mydict[item] += 1
print(mydict)

However, the output doesn't really increment the values and gives me this:

{'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1}

I thought when it loops through each item in the list, it should check the "if" statement every time, so I'm confused why it's not happening here.

Do you know if it's possible to make this work without using any of the function/method I mentioned above? Thank you so much!

Best,
Yuen

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

听不够的曲调 2025-01-22 16:37:26

您正在循环遍历列表,因此您要检查的值是 'a' 然后是 'b' 等等。其中每一项都不存在于字典中,因此它进入 if 子句并执行:mydict[item] = 1
如果您想查看值的更新,您需要多次检查同一个键。

You are looping through your list so the values you are checking are 'a' then 'b' and so on. Each one of those doesn't exist in the dict yet so it enters the if clause and does: mydict[item] = 1.
If you want to see the values getting updated you need to go over the same key more than once.

暖心男生 2025-01-22 16:37:26

在您的列表中,您有唯一的项目,如果您有重复的元素,您会看到您正在尝试执行的操作,即:

>>> import random
>>> a_list = ['a', 'b', 'c', 'd', 'e']
>>> my_dict = {}
>>> for item in [random.choice(a_list) for i in range(30)]:
...     try:
...             my_dict[item] += 1
...     except KeyError:
...             my_dict[item] = 1
...
>>> my_dict
{'a': 8, 'e': 5, 'd': 4, 'c': 12, 'b': 1}

不完全清楚的是,如果您想更新“键值”本身或关联的值该特定键值对的。

In your list you have items that are unique, if you have elements repeted, you would see what you are trying to do, i.e.:

>>> import random
>>> a_list = ['a', 'b', 'c', 'd', 'e']
>>> my_dict = {}
>>> for item in [random.choice(a_list) for i in range(30)]:
...     try:
...             my_dict[item] += 1
...     except KeyError:
...             my_dict[item] = 1
...
>>> my_dict
{'a': 8, 'e': 5, 'd': 4, 'c': 12, 'b': 1}

What is not entirely clear is, if you want to update the "Key value" itself or the associated value of that particular key-value pair.

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