Get key by value in dictionary

后端 未结 30 3142
北恋
北恋 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: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!
    

提交回复
热议问题