-4

I am trying to write a function where the Key of a dictionary is printed when the user inputs one of its values.

My dictionary is:

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

For for example if the user inputs 'John' then the student number c0952 will print.

Thanks!

vinnievienna
  • 1
  • 1
  • 2
  • 1
    What do you want to do in case of equal values. I doubt that there will be only one 'John'. – akg Mar 02 '17 at 19:29
  • 1
    the point of dictionaries is to look up values from a key, if you want to look up stuff from the person's name then make the name the key. (possibly as a separate dictionary) – Tadhg McDonald-Jensen Mar 02 '17 at 19:32
  • Possible duplicate of [Get key by value in dictionary](http://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary) – Tadhg McDonald-Jensen Mar 02 '17 at 19:36
  • i understand there might be equal values, however for this small project i am working on there is only one 'John'. – vinnievienna Mar 02 '17 at 19:37
  • Then: `print [x for x in student.keys() if 'John' in student[x]][0]` – akg Mar 02 '17 at 19:39

1 Answers1

1

Perhaps something like this:

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

Or, as akg mentioned, a one-liner using list comprehension:

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

Demo:

value? John
c0952

Using most of the answer from Get key by value in dictionary.

Community
  • 1
  • 1