Home > Software design >  Returning the Key with the highest Value from a List of Dictionaries
Returning the Key with the highest Value from a List of Dictionaries

Time:12-10

In this problem, you'll do the same thing, but with a more complex data structure. Your function should be called most_active, and it should have one parameter.

Instead of a dictionary, your parameter is a list of dictionaries. Every dictionary in the list will have exactly two keys: 'name' and 'days_active'. Your goal, as before, is to return the name of the most active student.

Some of the code you wrote on the previous problem will be reusable, but you'll need to modify it.

Hint: you do NOT need to iterate over the keys in the dictionaries inside the lists. You can always just access the_dict["name"] and the_dict["days_active"] directly. Your only loop should be the loop over the list.

#Add your code here!

def most_active(the_list):
    max_active = (max(the_list, key=lambda x: (["days_active"])))
    return max_active

    

Below are some lines of code that will test your function. You can change the value of the variable(s) to test your function with different inputs.

If your function works correctly, this will originally print:
Chopra, Deepak

the_list = [{"name": "Joyner, David", "days_active": 14},
            {"name": "Chopra, Deepak", "days_active": 22},
            {"name": "Winfrey, Oprah", "days_active": 17}]
print(most_active(the_list))

Currently my code returns the following: {'name': 'Joyner, David', 'days_active': 14} I have been working on this since yesterday and have tried many "solutions" but this is the closest I have gotten. Also, I have searched and searched on every conceivable forum and can't seem to figure this out...any and all help is appreciated.

CodePudding user response:

You can use something like this below,

the_list = [{"name": "Joyner, David", "days_active": 14},
            {"name": "Chopra, Deepak", "days_active": 22},
            {"name": "Winfrey, Oprah", "days_active": 17}]

print(max(the_list, key=lambda k: k['days_active']))

output will be

{'name': 'Chopra, Deepak', 'days_active': 22}

editing it, sorry didn't notice @Johnny Mopps comment. Thanks for the comment anyway

CodePudding user response:

This works:

def most_active(the_list):
    return max(the_list, key=lambda x: x["days_active"])

  • Related