Q12 Dictionaries

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]
if price in price_to_name:
price_to_name[price].append(name)
else:
price_to_name[price] = [name]

initialize the two laptops in the answer to None

laptop1 = None
laptop2 = None

look for a solution

for row in rows:
price = int(row[2])
# this laptop’s cost is price, so if there is a laptop that
# costs 5000 - price then their total price is exactly 5000
if price == 2500 and len(price_to_name[2500]) >= 2:
laptop1 = price_to_name[2500][0]
laptop2 = price_to_name[2500][1]
elif 5000 - price in price_to_name:
laptop1 = price_to_name[price][0]
laptop2 = price_to_name[5000 - price][0]
print(price)

print the solution

print(laptop1)
print(laptop2)

Can some one explain whats going on below?

elif 5000 - price in price_to_name: laptop1 = price_to_name[price][0] laptop2 = price_to_name[5000 - price][0]

Simply, This is just checking if the value 5000 - price is present as a key in the price_to_name dictionary or not.

Please @AntnioSDaCunha Wrap code snippet with ``` it will apply markdown format to easy to read and proper indentation for code.

GUIDELINE #1: Format all code using Markdown - no screenshots

It is almost impossible to read code that does not use Markdown. So do enclose any code inside a pair of ``` like this:

image

For Full guideline visit