如何创建返回有问题的value(key)的字典?

我必须根据自己的课程及其所属组的名称创建一个四人词典(在您的文件中)。 当我运行程序时,应该要求用户输入一个名称,然后将该人的组名返回给他们。它应该看起来像这样:

Welcome to the py-group-infromator,I can tell you where those users belong to:
{name_user}
{name_user}
{name_user}
{name_user}
Which user do you want to ask for?
{name_user}
{name_group}

开头

notes = ''' "Welcome to the py-group-informator,I can tell you where those users belong to" :
    Azura
    Mate
    Anna 
    John 
    " Which user do you want to ask for ?" '''
print(notes)

我的字典

people = [{'name': "Azura",'group': "cute_python"},{'name': "Mate",{'name': "Anna",'group': "fatal_error"},{'name': "John",'group': "fatal_error"}]

能帮助我吗?非常抱歉,这是我的第一个要求;)

advmen 回答:如何创建返回有问题的value(key)的字典?

与其他答案类似,但我会写出一些不同之处:

people = [
    {'name': "Azura",'group': "cute_python"},{'name': "Mate",{'name': "Anna",'group': "fatal_error"},{'name': "John",'group': "fatal_error"}
]
name_to_group = {d['name']: d['group'] for d in people}

print("Group Information")
names = ','.join(name_to_group)
name = input(f"Enter one of {names} or 0 to exit: ")
while name != '0':
    if name not in name_to_group:
        continue
    print(f"{name} is in group {name_to_group[name]}")
    name = input(f"Enter one of {names} or 0 to exit: ")
print('Good Bye')

示例输出:

Group Information
Enter one of Azura,Mate,Anna,John or 0 to exit: Mate
Mate is in group cute_python
Enter one of Azura,John or 0 to exit: John
John is in group fatal_error
Enter one of Azura,John or 0 to exit: 0
Good Bye
,

尝试一下:

people = [
    {'name': "Azura",'group': "fatal_error"}
]

def op(names):
    for value in people:
        if value['name'].lower() in names.lower():
            print(value['group'])

x = op(input("Welcome to the py-group-information,I can tell you where 
    those users belong to : Azura Mate  Anna   John Which user do you want 
    to ask for ?"))
,

以下是从您的数据结构中提取的核心逻辑(有意省略列表和欢迎屏幕文本)。假设您有这些,请首先捕获以下用户输入,然后继续搜索他们所属的组。

user_name = input("Which user do you want to ask for ?")
    for item in people:
        for key in item:
            if item[key] == user_name:
                    print(item['group'])
                    break
本文链接:https://www.f2er.com/3149129.html

大家都在问