简体   繁体   English

根据用户输入打印 dict 的特定元素?

[英]Print specific elements of dict based on user input?

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当前,循环 1 显示

Category chosen:  {'Audi': 'TT', 'Ferrari': 'Spider'}

and loop 2,和循环 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谢谢

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.")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM