0
How do I pull the values from a dictionary using the indexes for 2.2 Car Data Practice in the Intermediate python course?
I know that I can use the indexes and call them using the print function and the index in square brackets but i keep getting traceback errors
13 Answers
+ 2
Your if-else conditions are incorrect. At least in logic.
You're asking if the substring x is in the string supplied. For instance if the user input just the letter 'b' then x would be equal to 'b' and;
x in 'brand' would result in True.
If you want to see if a key exists in a dictionary then you would use something like;
if key in dict:
....
Where x is the key and car is the dict it would be;
if x in car:
...
Then, now that you know the key exists in the dict, you can use the key to get the value that is associated with it like;
dict[key]
Where car is the dict and x is the key you would use;
car[x]
If x was equal to 'brand' then this would return the value 'BMW'
+ 2
Hi please check this i simplified your code..
https://code.sololearn.com/cBLUH0FrLRu7/?ref=app
car = {
'brand':'BMW',
'year': 2018,
'color': 'red',
'mileage': 15000
}
x = input()
for info in car.keys():
if info == x:
print(car.get("{}".format(x)))
+ 1
Post the code please
+ 1
car = {
'brand':'BMW',
'year': 2018,
'color': 'red',
'mileage': 15000
}
x = input()
if x in "brand":
print ("BMW")
else:
if x in "year":
print ("2018")
else:
if x in "color":
print ("red")
else:
if x in "mileage":
print ("15000")
this is my code that works but i would like to be able to tell it to print the index instead of directly telling it what to print. Also i couldnt get the elif functions to work
+ 1
alright thank you
+ 1
Just print (car.brand)
+ 1
my solution:
car = {
'brand':'BMW',
'year': 2018,
'color': 'red',
'mileage': 15000
}
x = input()
print(car[x])
0
Post your try.. So that it helps to find mistakes...
0
Use elif short form
And use compare statement ==
Try this way.. Corrected code:
car = {
'brand':'BMW',
'year': 2018,
'color': 'red',
'mileage': 15000
}
x = input()
if x == "brand":
print ("BMW")
elif x == "year":
print ("2018")
elif x == "color":
print ("red")
elif x == "mileage":
print ("15000")
Brian
for finding index as a number, you can use loop by car.keys() as iterative indexes and use a counter for finding index as number by this way..
for i in car.keys():
if i == x :
print(i)
here car[i] will give you values....
0
how do i craft the code to print values using the index since I thought dictionaries are indexed like lists
0
Yes.
print( car['brand'] ) will output BMW
0
For such a simple operation, there are no iterations nor for loops necessary. Using nested if or elif statements, would solve the problem, but would also create some kind of a 'static code', which wont be related to the dictionary itself, but rather to the conditions of the if statements
This one is the easiest and correct way imo:
x = input()
print(car.get(x))