Search code examples
pythoncsvdictionarycs50title

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. 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

Solution

  • 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.