Get key by value in dictionary

后端 未结 30 2375
北恋
北恋 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 07:14

    Here is a solution which works both in Python 2 and Python 3:

    dict((v, k) for k, v in list.items())[search_age]
    

    The part until [search_age] constructs the reverse dictionary (where values are keys and vice-versa). You could create a helper method which will cache this reversed dictionary like so:

    def find_name(age, _rev_lookup=dict((v, k) for k, v in ages_by_name.items())):
        return _rev_lookup[age]
    

    or even more generally a factory which would create a by-age name lookup method for one or more of you lists

    def create_name_finder(ages_by_name):
        names_by_age = dict((v, k) for k, v in ages_by_name.items())
        def find_name(age):
          return names_by_age[age]
    

    so you would be able to do:

    find_teen_by_age = create_name_finder({'george':16,'amber':19})
    ...
    find_teen_by_age(search_age)
    

    Note that I renamed list to ages_by_name since the former is a predefined type.

    0 讨论(0)
  • 2020-11-21 07:15
    get_key = lambda v, d: next(k for k in d if d[k] is v)
    
    0 讨论(0)
  • 2020-11-21 07:16

    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.

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

    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!
    
    0 讨论(0)
  • 2020-11-21 07:17

    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)
    
    0 讨论(0)
  • 2020-11-21 07:18

    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.

    0 讨论(0)
提交回复
热议问题