Laptop Purchase (PP)

Screen Link:

My Code:

from csv import reader
file = open('laptops.csv')
file_reader = reader(file)
rows = list(file_reader)[1:]

price_to_name = {int(row[2]) : (row[1]) for row in rows}

What I expected to happen: Hi sir/ma’am, I cant go further than this in the practice problem, I would appreciate if someone explains me in easy terms also please let me know last line of my code is correct? I referred the topic related to this but I couldn’t understand. I would have visualized this but python tutor doesn’t read CSV files ( is there any way?). Thanks a lot for your help.

Hi @uditchauhan,

In the way you are doing it now (I mean your code line with the dictionary comprehension), you just re-write every time the value (which is a laptop name) of the key (which is a price). As a result, you’ll have a dictionary where to each unique price will correspond only one laptop name - the last encountered for that price. Instead, according to the question 2 of this mission screen, you have to build a dictionary where the key is the price, and the value is the list of all laptop names with that price (there can be more than one laptop with a given price). Hence, every time you have to append a new laptop name to a list of the others, with the same price, instead of just re-writing it using the dictionary comprehension.

1 Like

I am trying to understand your input on this, but i am not sure how to put it in code.

You can just re-write your code (which is now the dictionary comprehension), in this way:

price_to_name = {}
for row in rows:
    if int(row[2]) in price_to_name:
        price_to_name[int(row[2])] = [row[1]]

In this case, you append a laptop name to a list where the price already exists and assign it as a value where it doesn’t exist yet.

1 Like

Thank you for your quick help like always, lifesaver :slight_smile:,you have been the most helpful

1 Like

You are welcome Udit, I’m glad that it was helpful :blush: