972

I made a function which will look up ages in a Dictionary and show the matching name:

dictionary = {'george' : 16, 'amber' : 19}
search_age = raw_input("Provide age")
for age in dictionary.values():
    if age == search_age:
        name = dictionary[age]
        print name

I know how to compare and find the age I just don't know how to show the name of the person. Additionally, I am getting a KeyError because of line 5. I know it's not correct but I can't figure out how to make it search backwards.

4
  • Related: Reverse / invert a dictionary mapping
    – kojiro
    Commented Mar 15, 2020 at 3:50
  • 1
    Would you find a word based on its definition in a dictionary? NOPE. Commented Jun 5, 2020 at 0:54
  • You can't open a locked door. (Unless you break it ofcourse)
    – Buddy Bob
    Commented May 19, 2021 at 4:43
  • @JossieCalderon This just unlocked something I didn't realize I was missing.
    – Scone
    Commented Aug 22, 2023 at 13:34

43 Answers 43

992
mydict = {'george': 16, 'amber': 19}
print mydict.keys()[mydict.values().index(16)]  # Prints george

Or in Python 3.x:

mydict = {'george': 16, 'amber': 19}
print(list(mydict.keys())[list(mydict.values()).index(16)])  # Prints george

Basically, it separates the dictionary's values in a list, finds the position of the value you have, and gets the key at that position.

More about keys() and .values() in Python 3: How can I get list of values from dict?

14
  • 46
    Looks great but is it works always? I mean, do list.keys() and list.values() functions generate items in same order?
    – iskorum
    Commented Sep 23, 2013 at 14:01
  • 43
    Yes, they are guaranteed to be consistent. Additionally order is guaranteed not to change through iterations as long as the dictionary is not modified.
    – Veedrac
    Commented Sep 25, 2013 at 23:21
  • 19
    This looks to be a good solution but index gave only one value right, so if you ve multiple equal values, then it should return multiple keys right ? Commented Dec 13, 2013 at 13:17
  • 20
    @ArtOfWarfare docs.python.org/3/library/stdtypes.html#dict-views, "If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond."
    – Veedrac
    Commented Aug 6, 2015 at 19:14
  • 8
    @sinekonata: It still performs an expensive loop under the hood; the loop is just hidden inside the index method. Commented Apr 27, 2016 at 23:47
701

There is none. dict is not intended to be used this way.

dictionary = {'george': 16, 'amber': 19}
search_age = input("Provide age")
for name, age in dictionary.items():  # for name, age in dictionary.iteritems():  (for Python 2.x)
    if age == search_age:
        print(name)
11
  • 133
    I don't agree... agf's answer below is more constructive. A perfectly reasonable use case is not "unintended" (list comprehension fits such a use case anyway). A dict can be for multiple things at different times; keys and values have a clear meaning, of course, but "dict items with a given value" is a perfectly reasonable request. The recommendation to use a list of pairs would discard the context that one item is a 'definition' from the other, e.g. in parameter lists... Commented Oct 13, 2016 at 13:20
  • 11
    I do not agree with this answer. The fact that it is a possibility, as shown in answer by Stênio Elson, does not imply that it was not intended to be used as such. Not helpful at all. Commented Jan 8, 2020 at 17:52
  • Would you find a word in a dictionary based on its definition? NOPE. @Tropicalrambler Commented Jun 5, 2020 at 0:55
  • 9
    @JossieCalderon Yes. I often google the description of what I mean to get the word. This is essentially finding a word in a dictionary according to the definition.
    – David
    Commented Jun 17, 2020 at 14:24
  • 1
    @DavidIreland that only works because Google has made a reverse index of the entire internet. Commented Jun 11, 2021 at 19:20
359

If you want both the name and the age, you should be using .items() which gives you key (key, value) tuples:

for name, age in mydict.items():
    if age == search_age:
        print name

You can unpack the tuple into two separate variables right in the for loop, then match the age.

You should also consider reversing the dictionary if you're generally going to be looking up by age, and no two people have the same age:

{16: 'george', 19: 'amber'}

so you can look up the name for an age by just doing

mydict[search_age]

I've been calling it mydict instead of list because list is the name of a built-in type, and you shouldn't use that name for anything else.

You can even get a list of all people with a given age in one line:

[name for name, age in mydict.items() if age == search_age]

or if there is only one person with each age:

next((name for name, age in mydict.items() if age == search_age), None)

which will just give you None if there isn't anyone with that age.

Finally, if the dict is long and you're on Python 2, you should consider using .iteritems() instead of .items() as Cat Plus Plus did in his answer, since it doesn't need to make a copy of the list.

4
  • 12
    Correct, but if you're going to do linear search, you might as well replace the dict with a list of pairs.
    – Fred Foo
    Commented Nov 5, 2011 at 21:15
  • 13
    Unless your usual action is looking ages up by name, in which case a dict makes sense.
    – agf
    Commented Nov 5, 2011 at 21:16
  • 7
    It seems peculiar to assume that there is only one person with each age, while on the other hand, it is completely logical for each person to have a single age.
    – Dannid
    Commented Feb 9, 2016 at 1:30
  • @Dannid Yes, but the problem can be easily generalised. For example you could have a look up table with unique keys and their corresponding unique values. You can then look up things symmetrically value --> key or key --> value
    – pfabri
    Commented May 13, 2020 at 16:34
129

I thought it would be interesting to point out which methods are the quickest, and in what scenario:

Here's some tests I ran (on a 2012 MacBook Pro)

def method1(dict, search_age):
    for name, age in dict.iteritems():
        if age == search_age:
            return name

def method2(dict, search_age):
    return [name for name,age in dict.iteritems() if age == search_age]

def method3(dict, search_age):
    return dict.keys()[dict.values().index(search_age)]

Results from profile.run() on each method 100,000 times:

Method 1:

>>> profile.run("for i in range(0,100000): method1(dict, 16)")
     200004 function calls in 1.173 seconds

Method 2:

>>> profile.run("for i in range(0,100000): method2(dict, 16)")
     200004 function calls in 1.222 seconds

Method 3:

>>> profile.run("for i in range(0,100000): method3(dict, 16)")
     400004 function calls in 2.125 seconds

So this shows that for a small dict, method 1 is the quickest. This is most likely because it returns the first match, as opposed to all of the matches like method 2 (see note below).


Interestingly, performing the same tests on a dict I have with 2700 entries, I get quite different results (this time run 10,000 times):

Method 1:

>>> profile.run("for i in range(0,10000): method1(UIC_CRS,'7088380')")
     20004 function calls in 2.928 seconds

Method 2:

>>> profile.run("for i in range(0,10000): method2(UIC_CRS,'7088380')")
     20004 function calls in 3.872 seconds

Method 3:

>>> profile.run("for i in range(0,10000): method3(UIC_CRS,'7088380')")
     40004 function calls in 1.176 seconds

So here, method 3 is much faster. Just goes to show the size of your dict will affect which method you choose.

Notes:

  • Method 2 returns a list of all names, whereas methods 1 and 3 return only the first match.
  • I have not considered memory usage. I'm not sure if method 3 creates 2 extra lists (keys() and values()) and stores them in memory.
7
  • 10
    Just an update: it seems that dict.values() and dict.keys() both return lists that reference the objects from the original dict, so method 3 is also the one that uses the least memory (it only creates two thin list objects which wrap the contents of the dicts, whereas the others create iterator items
    – Patrick
    Commented Sep 10, 2013 at 4:28
  • 1
    I just wanted to benchmark it myself, scrolled down, bam there you have it. Thanks! Technically as you already pointed out method 2 doesn't do the exact same thing as 1 and 3 because it returns all matches. would be nice to see the results for e.g. return next([..]).
    – Ramon
    Commented Jun 23, 2015 at 8:33
  • 2
    @Martijn @Patrick, Since python 3.6, dict_keys dict_values do not have index attributes anymore, and you need to convert it first to a list, which will be memory hungry I guess (method 3). So it ends up like list(dict.keys())[list(dict.values()).index(search_age)] Commented May 3, 2021 at 8:43
  • 6
    @OrsirisdeJong dict.keys(), etc are dictionary view objects and have been so in all Python 3 releases, not just since 3.6. Don’t turn those into a list, use next((k for k, v in dict.items() if v == search_age), None) to find a match. Commented May 5, 2021 at 23:19
  • 3
    @MartijnPieters Indeed your solution is way less memory hungry than lists and replaces Method 3 well. Just a thing, you made an error inverting k and v. The correct version should be next((k for k, v in dict.items() if v == search_age), None). Anyway, thanks for the answer ;) Commented May 6, 2021 at 8:06
88

one line version: (i is an old dictionary, p is a reversed dictionary)

explanation : i.keys() and i.values() returns two lists with keys and values of the dictionary respectively. The zip function has the ability to tie together lists to produce a dictionary.

p = dict(zip(i.values(),i.keys()))

Warning : This will work only if the values are hashable and unique.

4
  • 2
    Yes, this will work: stackoverflow.com/questions/835092/… Commented Oct 25, 2013 at 7:52
  • 26
    ... and when there are no duplicate values.
    – ely
    Commented May 22, 2014 at 19:49
  • 4
    Beautiful. W.r.t the comment above, of course it only works when there are no duplicate values, but then, the question that started this thread makes the assumption that we have a one-to-one function, so given that assumption, this is the most elegant response by far. Commented Feb 10, 2017 at 17:10
  • 2
    expanding on hashable values: if your values are lists/sets convert them to tuple for this to work (they still need to be unique).
    – muon
    Commented Jul 12, 2018 at 15:31
48

I found this answer very effective but not very easy to read for me.

To make it more clear you can invert the key and the value of a dictionary. This is make the keys values and the values keys, as seen here.

mydict = {'george':16,'amber':19}
res = dict((v,k) for k,v in mydict.iteritems())
print(res[16]) # Prints george

or for Python 3, (thanks @kkgarg)

mydict = {'george':16,'amber':19}
res = dict((v,k) for k,v in mydict.items())
print(res[16]) # Prints george

Also

print(res.get(16)) # Prints george

which is essentially the same that this other answer.

3
  • 7
    This might not work if you have duplicate values like {'george':16,'amber':19,'jack':16}
    – Println
    Commented May 18, 2021 at 6:39
  • It will indeed only return one value even if there were duplicate values.
    – sinekonata
    Commented Jul 4, 2021 at 16:09
  • 2
    Or you can just do this in Python 3: [k for k, v in dictionary.items() if v == 16])
    – Feline
    Commented Oct 28, 2021 at 12:13
41
a = {'a':1,'b':2,'c':3}
{v:k for k, v in a.items()}[1]

or better

{k:v for k, v in a.items() if v == 1}
2
  • 6
    What if there is another key which holds the same value of a? May be pythonic way. But not a good idea.
    – gwthm.in
    Commented Dec 18, 2016 at 22:37
  • good point, i added solution which works with nonunique values
    – Jelen
    Commented Apr 21, 2017 at 13:03
37
key = next((k for k in my_dict if my_dict[k] == val), None)
2
  • Can I also have an 'else' in this same line? For the case when my value is not in the dict values Commented Jun 21, 2018 at 7:14
  • 1
    lKey = [k for k, v in lDictionary.iteritems() if v == lValue][0] or 'else-key'
    – faham
    Commented Jun 21, 2018 at 16:45
25

Try this one-liner to reverse a dictionary:

reversed_dictionary = dict(map(reversed, dictionary.items()))
2
  • 1
    This worked great for my encryption and decryption program, thank you! Commented Dec 8, 2019 at 11:50
  • Very neat alternative to dict(zip(dictionary.values(), dictionary.keys()))! How about speed? Commented Oct 31, 2022 at 15:11
16

If you want to find the key by the value, you can use a dictionary comprehension to create a lookup dictionary and then use that to find the key from the value.

lookup = {value: key for key, value in self.data}
lookup[value]
0
15

we can get the Key of dict by :

def getKey(dct,value):
     return [key for key in dct if (dct[key] == value)]
1
  • 2
    Easy and simple to understand that works for unique values.
    – not2qubit
    Commented Nov 10, 2020 at 1:00
12

You can get key by using dict.keys(), dict.values() and list.index() methods, see code samples below:

names_dict = {'george':16,'amber':19}
search_age = int(raw_input("Provide age"))
key = names_dict.keys()[names_dict.values().index(search_age)]
4
  • 2
    you don't use defined search_age var on next line... Maybe you should replace value with search_age?
    – Andersson
    Commented Apr 6, 2016 at 11:04
  • 3
    I get this error: 'dict_values' object has no attribute 'index' Commented Aug 11, 2017 at 12:21
  • @Blue_Elephant could you please provide code snippet you've got error and python version ( also print of type(dict_values) would be useful ) ? Commented Aug 11, 2017 at 16:05
  • 1
    changing names_dict.values().index(search_age) to list(names_dict.values()).index(search_age) solves the problem @Blue_Elephant raised. Commented Jul 26, 2021 at 20:00
11

Here is my take on this problem. :) I have just started learning Python, so I call this:

"The Understandable for beginners" solution.

#Code without comments.

list1 = {'george':16,'amber':19, 'Garry':19}
search_age = raw_input("Provide age: ")
print
search_age = int(search_age)

listByAge = {}

for name, age in list1.items():
    if age == search_age:
        age = str(age)
        results = name + " " +age
        print results

        age2 = int(age)
        listByAge[name] = listByAge.get(name,0)+age2

print
print listByAge

.

#Code with comments.
#I've added another name with the same age to the list.
list1 = {'george':16,'amber':19, 'Garry':19}
#Original code.
search_age = raw_input("Provide age: ")
print
#Because raw_input gives a string, we need to convert it to int,
#so we can search the dictionary list with it.
search_age = int(search_age)

#Here we define another empty dictionary, to store the results in a more 
#permanent way.
listByAge = {}

#We use double variable iteration, so we get both the name and age 
#on each run of the loop.
for name, age in list1.items():
    #Here we check if the User Defined age = the age parameter 
    #for this run of the loop.
    if age == search_age:
        #Here we convert Age back to string, because we will concatenate it 
        #with the person's name. 
        age = str(age)
        #Here we concatenate.
        results = name + " " +age
        #If you want just the names and ages displayed you can delete
        #the code after "print results". If you want them stored, don't...
        print results

        #Here we create a second variable that uses the value of
        #the age for the current person in the list.
        #For example if "Anna" is "10", age2 = 10,
        #integer value which we can use in addition.
        age2 = int(age)
        #Here we use the method that checks or creates values in dictionaries.
        #We create a new entry for each name that matches the User Defined Age
        #with default value of 0, and then we add the value from age2.
        listByAge[name] = listByAge.get(name,0)+age2

#Here we print the new dictionary with the users with User Defined Age.
print
print listByAge

.

#Results
Running: *\test.py (Thu Jun 06 05:10:02 2013)

Provide age: 19

amber 19
Garry 19

{'amber': 19, 'Garry': 19}

Execution Successful!
11
get_key = lambda v, d: next(k for k in d if d[k] is v)
3
  • Nice one-liner. However, is should be used only for equality testing of singletons (None, True, False etc.). The fact that CPython reuses string literals (and therefore a = 'foobar'; a is 'foobar' is True) is an implementation detail and should not be relied on.
    – piit79
    Commented Nov 18, 2019 at 11:42
  • 1
    And one more comment: get_key will throw StopIteration if the value doesn't exist in the dictionary - it would be better to use next(..., None) which would return None if the value wasn't found.
    – piit79
    Commented Nov 18, 2019 at 12:00
  • A slight modification will work if the dictionary doesn't contains single elements but sets: get_first_key = lambda v, d: next((k for k in d if (v in d[k] is not None)), None)
    – supernova
    Commented May 5, 2020 at 16:59
10

One line solution using list comprehension, which returns multiple keys if the value is possibly present multiple times.

[key for key,value in mydict.items() if value == 16]
9

Consider using Pandas. As stated in William McKinney's "Python for Data Analysis'

Another way to think about a Series is as a fixed-length, ordered dict, as it is a mapping of index values to data values. It can be used in many contexts where you might use a dict.

import pandas as pd
list = {'george':16,'amber':19}
lookup_list = pd.Series(list)

To query your series do the following:

lookup_list[lookup_list.values == 19]

Which yields:

Out[1]: 
amber    19
dtype: int64

If you need to do anything else with the output transforming the answer into a list might be useful:

answer = lookup_list[lookup_list.values == 19].index
answer = pd.Index.tolist(answer)
1
  • He's the creator of pandas. He's more commonly known as Wes, though.
    – Axel
    Commented Feb 7, 2019 at 19:14
7
d= {'george':16,'amber':19}

dict((v,k) for k,v in d.items()).get(16)

The output is as follows:

-> prints george
1
  • [k for k, v in d.items() if v==16]
    – auro
    Commented Feb 7, 2017 at 21:00
7

Here, recover_key takes dictionary and value to find in dictionary. We then loop over the keys in dictionary and make a comparison with that of value and return that particular key.

def recover_key(dicty,value):
    for a_key in dicty.keys():
        if (dicty[a_key] == value):
            return a_key
0
6
for name in mydict:
    if mydict[name] == search_age:
        print(name) 
        #or do something else with it. 
        #if in a function append to a temporary list, 
        #then after the loop return the list
1
  • 1
    Using a for loop and append is much slower than a list comprehension and it's also longer. Commented May 16, 2013 at 20:47
6
my_dict = {'A': 19, 'B': 28, 'carson': 28}
search_age = 28

take only one

name = next((name for name, age in my_dict.items() if age == search_age), None)
print(name)  # 'B'

get multiple data

name_list = [name for name, age in filter(lambda item: item[1] == search_age, my_dict.items())]
print(name_list)  # ['B', 'carson']
1
  • Thanks for your multiple keys solution.
    – Identicon
    Commented Apr 2, 2022 at 0:06
5

I glimpsed all answers and none mentioned simply using list comprehension?

This Pythonic one-line solution can return all keys for any number of given values (tested in Python 3.9.1):

>>> dictionary = {'george' : 16, 'amber' : 19, 'frank': 19}
>>>
>>> age = 19
>>> name = [k for k in dictionary.keys() if dictionary[k] == age]; name
['george', 'frank']
>>>
>>> age = (16, 19)
>>> name = [k for k in dictionary.keys() if dictionary[k] in age]; name
['george', 'amber', 'frank']
>>>
>>> age = (22, 25)
>>> name = [k for k in dictionary.keys() if dictionary[k] in age]; name
[]
4

it's answered, but it could be done with a fancy 'map/reduce' use, e.g.:

def find_key(value, dictionary):
    return reduce(lambda x, y: x if x is not None else y,
                  map(lambda x: x[0] if x[1] == value else None, 
                      dictionary.iteritems()))
4

I tried to read as many solutions as I can to prevent giving duplicate answer. However, if you are working on a dictionary which values are contained in lists and if you want to get keys that have a particular element you could do this:

d = {'Adams': [18, 29, 30],
     'Allen': [9, 27],
     'Anderson': [24, 26],
     'Bailey': [7, 30],
     'Baker': [31, 7, 10, 19],
     'Barnes': [22, 31, 10, 21],
     'Bell': [2, 24, 17, 26]}

Now lets find names that have 24 in their values.

for key in d.keys():    
    if 24 in d[key]:
        print(key)

This would work with multiple values as well.

4

Just my answer in lambda and filter.

filter( lambda x, dictionary=dictionary, search_age=int(search_age): dictionary[x] == search_age  , dictionary )
4

As someone mentioned there might be more than one key that have the same value, like my_dict below. Moreover, there might be no matching key.

my_dict ={'k1':1,'k2':2, 'k3':1, 'k4':12, 'k5':1, 'k6':1, 'k7':12}

Here are three ways of finding a key, one for the last hit, and two for the first.

def find_last(search_value:int, d:dict):
    
    return [x for x,y in d.items() if y==search_value].pop()

def find_first1(search_value:int, d:dict):
    return next(filter(lambda x: d[x]==search_value, d.keys()), None)

def find_first2(search_value:int, d:dict):
    return next(x for x,y in  d.items() if y==search_value)

Of these find_first1 is a bit faster than the others, and will return None in case there is no matching key.

3

already been answered, but since several people mentioned reversing the dictionary, here's how you do it in one line (assuming 1:1 mapping) and some various perf data:

python 2.6:

reversedict = dict([(value, key) for key, value in mydict.iteritems()])

2.7+:

reversedict = {value:key for key, value in mydict.iteritems()}

if you think it's not 1:1, you can still create a reasonable reverse mapping with a couple lines:

reversedict = defaultdict(list)
[reversedict[value].append(key) for key, value in mydict.iteritems()]

how slow is this: slower than a simple search, but not nearly as slow as you'd think - on a 'straight' 100000 entry dictionary, a 'fast' search (i.e. looking for a value that should be early in the keys) was about 10x faster than reversing the entire dictionary, and a 'slow' search (towards the end) about 4-5x faster. So after at most about 10 lookups, it's paid for itself.

the second version (with lists per item) takes about 2.5x as long as the simple version.

largedict = dict((x,x) for x in range(100000))

# Should be slow, has to search 90000 entries before it finds it
In [26]: %timeit largedict.keys()[largedict.values().index(90000)]
100 loops, best of 3: 4.81 ms per loop

# Should be fast, has to only search 9 entries to find it. 
In [27]: %timeit largedict.keys()[largedict.values().index(9)]
100 loops, best of 3: 2.94 ms per loop

# How about using iterkeys() instead of keys()?
# These are faster, because you don't have to create the entire keys array.
# You DO have to create the entire values array - more on that later.

In [31]: %timeit islice(largedict.iterkeys(), largedict.values().index(90000))
100 loops, best of 3: 3.38 ms per loop

In [32]: %timeit islice(largedict.iterkeys(), largedict.values().index(9))
1000 loops, best of 3: 1.48 ms per loop

In [24]: %timeit reversedict = dict([(value, key) for key, value in largedict.iteritems()])
10 loops, best of 3: 22.9 ms per loop

In [23]: %%timeit
....: reversedict = defaultdict(list)
....: [reversedict[value].append(key) for key, value in largedict.iteritems()]
....:
10 loops, best of 3: 53.6 ms per loop

Also had some interesting results with ifilter. Theoretically, ifilter should be faster, in that we can use itervalues() and possibly not have to create/go through the entire values list. In practice, the results were... odd...

In [72]: %%timeit
....: myf = ifilter(lambda x: x[1] == 90000, largedict.iteritems())
....: myf.next()[0]
....:
100 loops, best of 3: 15.1 ms per loop

In [73]: %%timeit
....: myf = ifilter(lambda x: x[1] == 9, largedict.iteritems())
....: myf.next()[0]
....:
100000 loops, best of 3: 2.36 us per loop

So, for small offsets, it was dramatically faster than any previous version (2.36 *u*S vs. a minimum of 1.48 *m*S for previous cases). However, for large offsets near the end of the list, it was dramatically slower (15.1ms vs. the same 1.48mS). The small savings at the low end is not worth the cost at the high end, imho.

2
  • I so much want this (reversedict = defaultdict(list) reversedict[value].append(key) for key, value in largedict.iteritems()] ) to work, but using Python 2.7.3, I get syntax error on the word 'for' Commented Jan 23, 2014 at 22:53
  • is that what you actually typed? you're missing a [ in it, if it is. otherwise, make sure it's on two lines, or put a ; between them if it's not. Commented Jan 23, 2014 at 23:37
3

Cat Plus Plus mentioned that this isn't how a dictionary is intended to be used. Here's why:

The definition of a dictionary is analogous to that of a mapping in mathematics. In this case, a dict is a mapping of K (the set of keys) to V (the values) - but not vice versa. If you dereference a dict, you expect to get exactly one value returned. But, it is perfectly legal for different keys to map onto the same value, e.g.:

d = { k1 : v1, k2 : v2, k3 : v1}

When you look up a key by it's corresponding value, you're essentially inverting the dictionary. But a mapping isn't necessarily invertible! In this example, asking for the key corresponding to v1 could yield k1 or k3. Should you return both? Just the first one found? That's why indexof() is undefined for dictionaries.

If you know your data, you could do this. But an API can't assume that an arbitrary dictionary is invertible, hence the lack of such an operation.

3

here is my take on it. This is good for displaying multiple results just in case you need one. So I added the list as well

myList = {'george':16,'amber':19, 'rachel':19, 
           'david':15 }                         #Setting the dictionary
result=[]                                       #Making ready of the result list
search_age = int(input('Enter age '))

for keywords in myList.keys():
    if myList[keywords] ==search_age:
    result.append(keywords)                    #This part, we are making list of results

for res in result:                             #We are now printing the results
    print(res)

And that's it...

0
3

There is no easy way to find a key in a list by 'looking up' the value. However, if you know the value, iterating through the keys, you can look up values in the dictionary by the element. If D[element] where D is a dictionary object, is equal to the key you're trying to look up, you can execute some code.

D = {'Ali': 20, 'Marina': 12, 'George':16}
age = int(input('enter age:\t'))  
for element in D.keys():
    if D[element] == age:
        print(element)
3

You need to use a dictionary and reverse of that dictionary. It means you need another data structure. If you are in python 3, use enum module but if you are using python 2.7 use enum34 which is back ported for python 2.

Example:

from enum import Enum

class Color(Enum): 
    red = 1 
    green = 2 
    blue = 3

>>> print(Color.red) 
Color.red

>>> print(repr(Color.red)) 
<color.red: 1=""> 

>>> type(Color.red) 
<enum 'color'=""> 
>>> isinstance(Color.green, Color) 
True 

>>> member = Color.red 
>>> member.name 
'red' 
>>> member.value 
1 

Not the answer you're looking for? Browse other questions tagged or ask your own question.