Laptop purchase practice problem in Python fundamentals

from csv import reader

read the CSV file

file = open(“laptops.csv”)
file_reader = reader(file)
rows = list(file_reader)[1:] # ignore column headers

create the dictionary mapping the prices to the laptop names

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

initialize the two laptops in the answer to None

laptop1 = None
laptop2 = None
total = 0

for each in price_to_name:
for row in price_to_name:
total = each + row

    if price_to_name[each] != price_to_name[row]:
        if each + row == 5000:
            laptop1 = price_to_name[each]
            laptop2 = price_to_name[row]

Help please. what is wrong with this? I am adding up prices to check if it is 5000 and checking the name is not same but it does not give proper result.

1 Like

You are doing wrong in dictionary mapping. You can try this. -
price_to_name = {}
for row in rows:
price = int(row[2])
name = row[1]
if price in price_to_name:
price_to_name[price].append(name)
else:
price_to_name[price] = [name]
After correction try the next part.If you get this information useful ,then please mark this as a solution.

1 Like

I see this in the solution but I thought there is another way. Instead of creating a list for the same price laptops, I am appending the key value pair again. so there may be duplicate keys. Is this not allowed?

Hi @desihomeinfraNKLIN,

The issue with your code starts exactly in the first for-loop. In this way, you are not appending a new key-value pair with a duplicated key (which Python doesn’t support, by the way), but you are actually re-assigning the value of an already existing key (which is a unique price, in this case). Instead, the idea of creating a list of laptop names for the same price, as it suggested in the solution, looks reasonable.

1 Like

Thank you for the explanation

1 Like