关于Python字典中键值自增的问题
我是 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在循环遍历列表,因此您要检查的值是
'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 theif
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.
在您的列表中,您有唯一的项目,如果您有重复的元素,您会看到您正在尝试执行的操作,即:
不完全清楚的是,如果您想更新“键值”本身或关联的值该特定键值对的。
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.:
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.