Home > Blockchain >  Python dictionary initialization in CS50 course content
Python dictionary initialization in CS50 course content

Time:03-03

The following code is taken from week 7 of CS50. It opens a file (favorites.csv), reads the titles of common television shows from the file, and adds the titles and counts of the titles to a dictionary. However, I don't understand why it works. At the start, the titles dictionary is initialized. Later the count is added to the dictionary if the title is in the titles dictionary. However, I can't understand why the titles dictionary includes any titles? Where were the titles from the favorites.csv file added to the dictionary? I would have thought that the "if title in titles" conditional would always be false because at this point it appears the dictionary is empty? A little embarrased to be asking this but I'm obviously not understanding this after a fair amount of time researching the issue. Thanks for any explanations offered.

# Prints popularity of titles in CSV, sorted by title

import csv

# For accumulating (and later sorting) titles
titles = {}

# Open CSV file
with open("favorites.csv", "r") as file:

    # Create DictReader
    reader = csv.DictReader(file)

    # Iterate over CSV file, adding each (uppercased) title to dictionary
    for row in reader:

        # Canoncalize title
        title = row["title"].strip().upper()

        # Count title
        if title in titles:
            titles[title]  = 1
        else:
            titles[title] = 1

# Print titles in sorted order
for title in sorted(titles):
    print(title, titles[title])

CodePudding user response:

When

if title in titles:

is False, the else branch runs:

titles[title] = 1

this adds the title to the dictionary.

  • Related