I made a function which will look up ages in a Dictionary
and show the matching name:
dictionary = {\'george\' : 16, \'amber\' : 19}
search_age
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)
def get_Value(dic,value):
for name in dic:
if dic[name] == value:
del dic[name]
return name
key = next((k for k in my_dict if my_dict[k] == val), None)
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
mydict = {'george':16,'amber':19}
dict((v,k) for k,v in mydict.iteritems())[16]
which is essentially the same that this other answer.
Try this one-liner to reverse a dictionary:
reversed_dictionary = dict(map(reversed, dictionary.items()))
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]