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

时间:2016-08-29 16:05:37

标签: 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('Hello,', dict[inn])
    else :
       print('Sorry, you are not a member')

期望的结果

Enter your ID : aa
Hello, Mark Roch

感谢您的帮助

4 个答案:

答案 0 :(得分:3)

没有必要遍历字典中的所有项目;在FirstnameLastname字段中查找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')

一些建议:

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

members = [
    {'id': 'aa', 'Firstname': 'Mark',  'Lastname': 'Roch'},
    {'id': 'bb', 'Firstname': 'Jamal', 'Lastname': 'borh'},
    {'id': 'cc', 'Firstname': 'Van',   'Lastname': 'nilsa'},
]

不要将字典dict命名,因为它与内置函数名称冲突。

答案 1 :(得分:3)

请检查以下代码并注明内容。

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>

答案 2 :(得分:0)

代码的工作版本应为:

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

您的代码的泄露/问题:

  1. for d in dict表示for d in dict.keys(),将返回['id', 'FirstName', 'LastName'。为了迭代id,你应该做for d in dict['id']。实际上,不需要迭代列表本身。要获取; {list}中的index元素,您只需使用list.index(element)函数
  2. 即可
  3. dictbuilt-in中的python类。你永远不应该使用关键字
  4. 你的词典结构本身并不正确。根据定义,dict means collections of objects和对象意味着类似的实体。在这种情况下,人。因为id是唯一的假设,所以我用嵌套的dict作为id的键(你也可以使用dict列表):

    {'aa': {'Firstname' : 'Mark',
            'Lastname' : 'Roch'},
     'bb': {'Firstname' : 'Jamal',
            'Lastname' : 'borh'},
     'cc': {'Firstname' : 'Van',
            'Lastname' : 'nilsa'},
    }
    

答案 3 :(得分:0)

previous posts

为基础
h[k] = h[k] + 1 #=> h[k] = 3 + 1

注意:您无法为字典iin = input('Enter your ID :') dict = {'id' : ['aa', 'bb', 'cc'], 'Firstname' : ['Mark', 'Jamal', 'Van'], 'Lastname' : ['Roch', 'borh', 'nilsa']} try: i = dict['id'].index(iin) print('Hello {0} {1}'.format(dict['Firstname'][i], dict['Lastname'][i]) except ValueError: print('Sorry, you are not a member') 命名,因为它与关键字冲突。