+ 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")
6 Respostas
+ 9
if a in car:
print(car[a])
+ 5
Another option:
car = {
'brand':'BMW',
'year': 2018,
'color': 'red',
'mileage': 15000
}
print(car[input()])
+ 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.
+ 1
Rik Wittkopp thanks
+ 1
Mir Abir Hossain thank you
0
visph thanks