0

I don't understand what the problem. Can someone please help??

car = { 'brand':'BMW', 'year': 2018, 'color': 'red', 'mileage': 15000 } if 'brand' in car: print ('BMW') else: if 'year' in car: print (2018) else: if 'color' in car: print ('red') else: if 'mileage' in car: print (15000)

27th Jun 2021, 6:43 PM
Gee Pebbles
Gee Pebbles - avatar
10 Antworten
+ 6
Your code needs to take the key as input and output the corresponding value. key = input() Your data if key == "brand": print ('BMW') else: ...
28th Jun 2021, 2:01 AM
Simba
Simba - avatar
+ 3
"brand" is a key in the car dictionary. To access the associated value we use car["brand"]. So it would be if "brand" in car.keys(): print(car["brand"])
27th Jun 2021, 6:46 PM
Lisa
Lisa - avatar
+ 2
Your code will only print 'BMW' as it always evaluates to true coz the key " brand" exists in the dictionary 'car'. If u are confused membership check for dictionary, then let me make it clear, the 'in' operator checks whether a key exists in a dictionary. brand, year, color, mileage are keys while BMW,2018, red, 15000 are values
27th Jun 2021, 6:57 PM
Kirabo Ibrahim
Kirabo Ibrahim - avatar
+ 2
I tried yours Lisa but it didn't work
27th Jun 2021, 8:54 PM
Gee Pebbles
Gee Pebbles - avatar
+ 1
So how do I correct it?? Kirabo Ibrahim
27th Jun 2021, 9:03 PM
Gee Pebbles
Gee Pebbles - avatar
+ 1
According to me you wanted you wanted to print the details of the car if it only existed in the dictionary but the existence is based on the 'brand' key. Also u are using a dictionary to represent the car object and I will also assume you will have a collection of cars like this. [ {car_1}, {car_2}, ...{car_n} ] Let me assume the above, then the code would be like: brand = input() cars =[{car_1}, ..., {car_n}] for car in cars: if car['brand'] == brand: for k in car: print(car[k])
28th Jun 2021, 10:15 AM
Kirabo Ibrahim
Kirabo Ibrahim - avatar
+ 1
Thank you all🙂
28th Jun 2021, 2:05 PM
Gee Pebbles
Gee Pebbles - avatar
27th Jun 2021, 9:26 PM
Lisa
Lisa - avatar
0
You have 12000$ to buy a car. You are given a program which takes the price of car as an input.
17th Nov 2022, 4:56 PM
Ranjeet Kumar Chauhan
0
You have $12,000 to buy a car. You're given a program which takes the price of car as an input.
29th Nov 2022, 6:24 AM
MUTHUKUMAR M
MUTHUKUMAR M - avatar