如何使用python从字典中获取特定键的值

如何使用python从字典中获取特定键的值,python,for-loop,dictionary,input,output,Python,For Loop,Dictionary,Input,Output,在这段代码中,我想用ID标识一个成员。如果字典中有ID,我想打印这个成员的全名 iin = input('Enter your ID :') dict = {'id' : ['aa', 'bb', 'cc'], 'Firstname' : ['Mark', 'Jamal', 'Van'], 'Lastname' : ['Roch', 'borh', 'nilsa']} for d in dict: if inn in d: print('

在这段代码中,我想用ID标识一个成员。如果字典中有ID,我想打印这个成员的全名

iin = input('Enter your ID :')
 dict = {'id' : ['aa', 'bb', 'cc'],
        'Firstname' : ['Mark', 'Jamal', 'Van'],
        'Lastname' : ['Roch', 'borh', 'nilsa']}
 for d in dict:
    if inn in d:
       print('Hello,', dict[inn])
    else :
       print('Sorry, you are not a member')
期望的结果

Enter your ID : aa
Hello, Mark Roch

感谢您的帮助

代码的工作版本应为:

my_dict = {'id' : ['aa', 'bb', 'cc'],
           'Firstname' : ['Mark', 'Jamal', 'Van'],
               'Lastname' : ['Roch', 'borh', 'nilsa']}
iin = input('Enter your ID :')
# Enter your ID :"bb"
try:
    my_id = my_dict['id'].index(iin)
    print my_dict['Firstname'][my_id], ', ', my_dict['Lastname'][my_id]
except ValueError:
    print 'Sorry, you are not a member'    
# Jamal ,  borh
对代码的解释/问题:

  • for d in dict
    表示
    for d in dict.keys()
    将返回
    ['id','FirstName','LastName'
    。为了在id上迭代,您应该对dict['id'中的d执行
    。事实上,不需要迭代列表本身。要获取列表中元素的
    索引
    ,只需使用
    list.index(element)
    函数即可
  • dict
    python
    中的
    内置类。千万不要使用关键字
  • 您的字典结构本身不正确。根据定义,
    dict表示对象的集合
    ,而object表示类似的实体。在这种情况下,Person。由于id被假定为唯一的,因此在am中,使用键为
    id
    的嵌套dict(您也可以使用dict列表):


  • 不需要遍历字典中的所有项;在
    Firstname
    Lastname
    字段中查找id是愚蠢的。(如果输入的id恰好是某人姓名的子字符串,则可能会产生错误的结果。)

    您需要检查给定的id是否存在于id列表中,如果存在,请使用该列表位置打印相应的名字和姓氏:

    if iin in dict['id']:
       index = dict['id'].index(iin)
       print('Hello, %s %s' % (dict['Firstname'][index], dict['Lastname'][index]))
    else :
       print('Sorry, you are not a member')
    
    一些建议:

    如果您将数据排列为包含单个成员的DICT列表,可能会更容易,如下所示:

    members = [
        {'id': 'aa', 'Firstname': 'Mark',  'Lastname': 'Roch'},
        {'id': 'bb', 'Firstname': 'Jamal', 'Lastname': 'borh'},
        {'id': 'cc', 'Firstname': 'Van',   'Lastname': 'nilsa'},
    ]
    
    不要给字典命名为dict,因为它与内置函数名冲突。

    基于


    注意:您无法命名字典
    dict
    ,因为它与关键字冲突。

    请检查以下代码,并内联注释

    iin = input('Enter your ID :')
    d = {'id' : ['aa', 'bb', 'cc'],
            'Firstname' : ['Mark', 'Jamal', 'Van'],
            'Lastname' : ['Roch', 'borh', 'nilsa']}
    #Get list of IDs    
    id_list = d['id']
    
    #Check input in list
    if iin in id_list:
        #Get index of input from ID list
        index = id_list.index(iin)
        #Get rest of info
        fname = d['Firstname'][index]
        lname = d['Lastname'][index]
        msg = "Hello, " + fname + " " + lname
        print msg
    else:
        print 'Sorry, you are not a member'
    
    输出:

    C:\Users\dinesh_pundkar\Desktop>python b.py
    Enter your ID :"aa"
    Hello, Mark Roch
    
    C:\Users\dinesh_pundkar\Desktop>python b.py
    Enter your ID :"asd"
    Sorry, you are not a member
    
    C:\Users\dinesh_pundkar\Desktop>
    

    从第一个字典元素(列表)中获取ID的索引,并使用它访问其他列表:
    dict[“Firstname”][index]
    但是您的代码不会工作,因为
    d
    只获取字典键“ID”、“Firstname”等。您想测试ìn dict[d]`去列表。确实如此,但是我被卡住了。你能给我好的语法吗!thanks@K.ossama:我在回答中添加了一些解释。希望这些可以帮助您,因为您的代码存在一些基本的编程问题。如果输入id不存在,您应该捕获异常。@TerrenceBrannon:是的,我应该这样做。谢谢。更新了t答案
    dict
    是一个内置的类名,而不是关键字。正如你所说,覆盖它是一个坏主意。@mad物理学家:是的,它是一个类。更新了它。有人知道为什么我的答案被否决了吗?我遗漏了什么吗?
    dict
    是一个类名。
    dict(…)
    实际上是在调用初始值设定项和构造函数。谢谢@John Gorden的帮助!您的代码很清晰您可以命名字典
    dict
    ,但它会隐藏类的名称。
    dict
    不是关键字。谢谢@Dinesh Pundkar!代码现在运行得很好
    iin = input('Enter your ID :')
    d = {'id' : ['aa', 'bb', 'cc'],
            'Firstname' : ['Mark', 'Jamal', 'Van'],
            'Lastname' : ['Roch', 'borh', 'nilsa']}
    #Get list of IDs    
    id_list = d['id']
    
    #Check input in list
    if iin in id_list:
        #Get index of input from ID list
        index = id_list.index(iin)
        #Get rest of info
        fname = d['Firstname'][index]
        lname = d['Lastname'][index]
        msg = "Hello, " + fname + " " + lname
        print msg
    else:
        print 'Sorry, you are not a member'
    
    C:\Users\dinesh_pundkar\Desktop>python b.py
    Enter your ID :"aa"
    Hello, Mark Roch
    
    C:\Users\dinesh_pundkar\Desktop>python b.py
    Enter your ID :"asd"
    Sorry, you are not a member
    
    C:\Users\dinesh_pundkar\Desktop>