Get key by value in dictionary

后端 未结 30 2373
北恋
北恋 2020-11-21 06:28

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

dictionary = {\'george\' : 16, \'amber\' : 19}
search_age          


        
相关标签:
30条回答
  • 2020-11-21 06:56

    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)
    
    0 讨论(0)
  • 2020-11-21 06:56
    def get_Value(dic,value):
        for name in dic:
            if dic[name] == value:
                del dic[name]
                return name
    
    0 讨论(0)
  • 2020-11-21 06:57
    key = next((k for k in my_dict if my_dict[k] == val), None)
    
    0 讨论(0)
  • 2020-11-21 06:57

    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.

    0 讨论(0)
  • 2020-11-21 07:02

    Try this one-liner to reverse a dictionary:

    reversed_dictionary = dict(map(reversed, dictionary.items()))
    
    0 讨论(0)
  • 2020-11-21 07:02

    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 讨论(0)
提交回复
热议问题