Need explanation how this line of code works in Python for Dictionary

Question:

This is the code for the project I am doing.
I don’t understand how the last section of this code works. Any help will be appreciated.

The dictionaries are as follows:

names = {}

people = {}

movies = {}

def load_data(directory):
    """
    Load data from CSV files into memory.
    """
    # Load people
    with open(f"{directory}/people.csv", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            people[row["id"]] = {
                "name": row["name"],
                "birth": row["birth"],
                "movies": set()
            }
            if row["name"].lower() not in names:
                names[row["name"].lower()] = {row["id"]}
            else:
                names[row["name"].lower()].add(row["id"])
# Load movies
with open(f"{directory}/movies.csv", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        movies[row["id"]] = {
            "title": row["title"],
            "year": row["year"],
            "stars": set()
        }

# Load stars
with open(f"{directory}/stars.csv", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        try:
            people[row["person_id"]]["movies"].add(row["movie_id"])
            movies[row["movie_id"]]["stars"].add(row["person_id"])
        except KeyError:
            pass

what is the people[row["person_id"]]["movies"].add(row["movie_id"]) doing here?

Asked By: Lucian_Blue

||

Answers:

people is a dictionary whose values are dictionaries, as you can see from:

people[row["id"]] = {
    "name": row["name"],
    "birth": row["birth"],
    "movies": set()
}

The movies element of this dictionary is a set. The .add() method is how you add a new element to a set.

So

people[row["person_id"]]["movies"].add(row["movie_id"])

gets the movies set for the person ID in the current row, and adds the movie ID to the set of all their movies.

Similarly, the next line

movies[row["movie_id"]]["stars"].add(row["person_id"])

adds the star to the set of stars of the current movie.

This allows you to use the people dictionary to find all the movies that someone has starred in, and use the movies dictionary to find all the stars of a movie.

Answered By: Barmar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.