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. 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?:
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
CodePudding user response:
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. 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?
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. But your first version is doing the opposite, which will throw you an error.
CodePudding user response:
If titles
is a dictionary titles[title]
finds the value corresponding to the key title
. Your second version does not put anything in the dictionary, so titles[title]
raises a key error.
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
:
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. You no longer have key, value pairs, just items.