I'm creating a vehicle rental program, I have a dictionary containing cars.
car_dict = {'Sports': {'Audi': 'TT', 'Ferrari':'Spider'},
'Luxry': {'Mercedes':'S-Class','Rollys Royce':'Phantom'},
I have two loops to print but one is using user input and the other is not - I need to combine them, effectively, to display which category the user picks, so if they type "Sports", it shows
Category chosen:
--Sports--
>Audi TT
>Ferrari Spider
But right now, my two loops
u_input = input("Enter >> ")
if u_input in car_dict:
try:
print("Category chosen: ", car_dict[u_input])
except KeyError:
print("Not an existing category, sorry.")
for key, value in car_dict.items():
if key == 'Sports':
print("--", key, "Cars --")
for pair in value.items():
print(*pair)
they print differently and I need a combination of both? If that makes sense. Currently, loop 1 displays
Category chosen: {'Audi': 'TT', 'Ferrari': 'Spider'}
and loop 2,
--Sports--
Audi TT
Ferrari Spider
The latter NOT taking input. How would I get around this? Take user input and display the matching category like the second loop. I can't seem to figure it out. Thanks
CodePudding user response:
There's no need for the second loop, just use the element selected using the user input.
u_input = input("Enter >> ")
if u_input in car_dict:
print(f"Category chosen:\n--{u_input}--")
for make, model in car_dict[u_input]:
print(f'>{make} {model}')
else:
print("Not an existing category, sorry.")