+ 5
Can u use for loop here (python dictionary problem)[SOLVED]
x=input() car = { 'brand':'BMW', 'year': 2018, 'color': 'red', 'mileage': 15000 } if (x=='year'): print(car['year']) elif x=='color': print(car['color']) elif x=='mileage': print(car['mileage']) elif x=='brand': print(car['brand'])
20 odpowiedzi
+ 8
you could use loop for this task, but the more pythonic way would be to use dict.get(key) method ;)
+ 6
You in no way need a loop, but here.
https://code.sololearn.com/cxsxz91F8iaq/?ref=app
+ 6
key = input()
car = {
'brand':'BMW',
'year': 2018,
'color': 'red',
'mileage': 15000
}
for k, v in car.items():
if k==key:
print(v)
... or few shorter (but onelined):
print(next(v for k, v in car.items if k==key))
+ 6
Goku ,
Yes, you can surely use for loops.
Everyone has already shown above 👆 how it can be solved in different ways using for loops.
+ 4
Goku
Yes you can use loop even you can directly get the value by just passing key as car is a dictionary.
See this
-------1st way------
for i in car:
if i == x:
print (car[i])
-------2nd way--------
print (car[x])
+ 4
Slick
You can also iterate dictionary like this
for key in car:
print (key)
So here input can be compare with key but not with key: value pair as you said
+ 4
Goku,
As others have mentioned, use of loop is possible, but its necessity should be considered thoroughly. For example, if you want to print the key-value pairs from dictionary <car> you can do
for ( key, value ) in car.items():
print( f"{key} : {value}" )
But if you only want to output one of the pairs (if any match), you can use subscript operator [], or use `get()` method https://www.w3schools.com/JUMP_LINK__&&__python__&&__JUMP_LINK/ref_dictionary_get.asp
+ 3
Your program needs to take the key as input and output the corresponding value.
Sample Input:
year
Sample Output:
2018
Question ☝️
+ 3
Shivani 📚✍ [Exams]
I got the output using if ..but can we add loop in this task
+ 3
Goku,
Why you think we need a loop there? I don't get why we need a loop though;
+ 3
Ipang
I just want to know that we can use loop or not
+ 3
🅘🅜 🅰🅹 !!! the input is a string and that code would comapre a string to a dict key:value pair. You could do car.keys() tho
+ 3
Slick
Well keys are also string so no problem here
+ 1
car = {...}
x = input()
# ~~~ Method 1:
print(x.get(x, "\0"))
# ~~~ Method 2:
if x in car: print(car[x])
# ~~~ Method 3 (slow):
[print(car[y]) for y in car if x == y]
# Hope this helps
0
Alot of ways we can use it, but the way you do is important.
0
car = {'brand':'BMW', 'year': 2018, 'color': 'red', 'mileage': 15}
key = input()
print(car[key])
- 3
I prefer to use switch instead if elif
- 3
hi
- 4
kelar kan komentat
- 4
deled