2017-03-02 71 views
-4

我想写一个函数,当用户输入其值之一时打印字典的密钥。如何通过用户输入值查找密钥

我的字典是:

student = {c0952: [18, 'John', 'Smith'], 
      c0968: [24, 'Sarah', 'Kelly'] 
      } 

对于例如,如果用户输入“约翰”,那么学生人数c0952打印。

谢谢!

+1

如果价值相等,您想做什么?我怀疑只会有一个'约翰'。 – akg

+1

字典的要点是从一个关键字查找值,如果你想从人的名字中查找东西,那么把这个名称作为关键字。 (可能作为一个单独的字典) –

+0

可能重复的[在字典中获取键值](http://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary) –

回答

1

也许是这样的:

student = { 'c0952': [18, 'John', 'Smith'], 
      'c0968': [24, 'Sarah', 'Kelly'] 
      } 

name_value = raw_input("value? ") 

for stu_num, names in student.iteritems(): 
    for name in names: 
     if name == name_value: 
      print stu_num 

或者,如akg mentioned,使用list comprehension一个班轮:

print [x for x in student.keys() if name_value in student[x]][0] 

演示:

价值?约翰
c0952

使用最多的答案从Get key by value in dictionary