[英]How is the value assigned to Dictionary?
This is a very simple problem where it reads file from a CSV with first column header as "title" and then counts how many times the title appears in side the dictionary.这是一个非常简单的问题,它从 CSV 中读取文件,第一列 header 作为“标题”,然后计算标题在字典中出现的次数。 But I am not understanding in which step it is assigning the "title" to "titles" dictionary.
但我不明白它在哪一步将“标题”分配给“标题”字典。
The code is:代码是:
import csv
titles = {}
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
#title is defined here
title = row["title"].strip().upper()
if title in titles:
titles[title] = titles[title] + 1
else:
titles[title] = 1
If it is assigning inside the else block then why is my second code where I just want to assign values to the dictionary named "titles" and not count the number of times it appears, is not Working?:如果它在 else 块内分配,那么为什么我的第二个代码只是想将值分配给名为“titles”的字典而不计算它出现的次数,这不起作用?:
import csv
titles = {}
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
#title is defined here
title = row["title"].strip().upper()
if not title in titles:
titles[title]
print(titles[title])
Error: Key Value error
In your second version, you have this line titles[title]
, which is not adding the title to your titles dictionary as you do in your first version.在你的第二个版本中,你有这一行
titles[title]
,它没有像你在第一个版本中那样将标题添加到你的 titles 字典中。 Since the title is missing in the dictionary, accessing it will give you a key value error.由于字典中缺少标题,因此访问它会出现键值错误。 Why do you have a line
titles[title]
that does nothing?为什么你有一行
titles[title]
什么都不做?
But I think there's a bigger problem here with your first version of code.但我认为您的第一个版本代码存在更大的问题。 You want to add the title to the dictionary when it's not already in it, and add the count by 1 if otherwise.
您想在字典中没有标题时将其添加到字典中,否则将计数加 1。 But your first version is doing the opposite, which will throw you an error.
但是您的第一个版本恰恰相反,这会引发错误。
If titles
is a dictionary titles[title]
finds the value corresponding to the key title
.如果
titles
是一个字典titles[title]
找到与键title
对应的值。 Your second version does not put anything in the dictionary, so titles[title]
raises a key error.您的第二个版本没有在字典中放入任何内容,因此
titles[title]
引发了一个关键错误。
You say you want to "assign values to the dictionary but not count anything".你说你想“给字典赋值但不计算任何东西”。 A dictionary is the wrong structure to use for this.
字典是用于此的错误结构。 If you want unique titles, you could use a
set
:如果你想要独特的标题,你可以使用一个
set
:
import csv
titles = set()
with open("movies.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
#title is defined here
title = row["title"].strip().upper()
titles.add(title)
print(titles)
Notice the add
method only adds something if it does not already exist in the set, rather like a mathematical set.请注意,
add
方法仅在集合中尚不存在的情况下才添加某些内容,就像数学集合一样。 You no longer have key, value pairs, just items.您不再有键、值对,只有项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.