+ 1

How to take keys of a dictionary as an user input

I am trying to take the keys of a dictionary as a input in a problem.some how i have passed all test cases but i am not satisfied.can anybody teach a more efficent code a=input() car = { 'brand':'BMW', 'year': 2018, 'color': 'red', 'mileage': 15000 } if a=="brand": print("BMW") elif a== "year": print("2018") elif a== "color": print("red") elif a=="mileage": print("15000")

9th Feb 2021, 6:15 AM
Guraja Teja Surya Lokesh Kumar
Guraja Teja Surya Lokesh Kumar - avatar
6 Antworten
+ 9
if a in car: print(car[a])
9th Feb 2021, 6:39 AM
visph
visph - avatar
+ 5
Another option: car = { 'brand':'BMW', 'year': 2018, 'color': 'red', 'mileage': 15000 } print(car[input()])
9th Feb 2021, 7:04 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
You can also write: if a in car.keys(): print(car[a]) You can also use a.lower() instead of a, as all the keys in the dictionary is lower case and if by mistake somebody puts a uppercase letter in the input, a.lower() will convert it into lower case.
9th Feb 2021, 7:47 AM
Mir Abir Hossain
Mir Abir Hossain - avatar
+ 1
9th Feb 2021, 7:11 AM
Guraja Teja Surya Lokesh Kumar
Guraja Teja Surya Lokesh Kumar - avatar
+ 1
9th Feb 2021, 8:07 AM
Guraja Teja Surya Lokesh Kumar
Guraja Teja Surya Lokesh Kumar - avatar
0
visph thanks
9th Feb 2021, 7:11 AM
Guraja Teja Surya Lokesh Kumar
Guraja Teja Surya Lokesh Kumar - avatar