Juozapas Bagdonas
Juozapas Bagdonas

Reputation: 1

Finding the highest value in a dictionary within a dictionary

There's a task in the beginner course where we have to find the highest value of a certain key in a dictionary.

The values, however, are located within another dictionary. So the format is something like this:

data = {
    'Country1': {2015: 5, 2016: 9, 2017: 2},
    'Country2': {2015: 20, 2016: 10, 2017: 5}
}

Of course there's more than two countries there, but essentially I have to find the highest value from a specific year (let's say 2015). Anyone with a quick idea on how to proceed? I've looked at several similar options like max() or lambda but I'm not sure how they could be used in this particular situation with a list within a list.

Upvotes: 0

Views: 80

Answers (3)

Smooth
Smooth

Reputation: 1

data = {'Country1': {2015: 5, 2016: 9, 2017: 2}, 'Country2': {2015: 20, 2016: 10, 2017: 5}}

max_val = 0
for _,inner_dict in data.items():
    max_val = max(inner_dict[2015], max_val)
print(max_val)

Iterating through the dictionary this way would minimize resource usage especially if you are dealing with a large data set

Upvotes: 0

asd asd
asd asd

Reputation: 146

You can do something like this:

data = {
    'Country1': {2015: 5, 2016: 9, 2017: 2},
    'Country2': {2015: 20, 2016: 10, 2017: 5}
}

country_with_max_2015 = max(data, key=lambda k: data[k][2015])

In the function max the lambda function will get values 'Country1' and 'Country2' which can be used to get the value of 'Country1' from data dict and so we can find the value of key 2015 in values of country.

Upvotes: 3

mitoRibo
mitoRibo

Reputation: 4548

You can use a for-loop to iterate through the dictionary of dictionaries I'll leave it up to you to decide how you want to keep track of the max values you find.

This is for python3, python2 will look a little different

data = {'Country1': {2015: 5, 2016: 9, 2017: 2}, 'Country2': {2015: 20, 2016: 10, 2017: 5}}

for country,sub_dict in data.items():
    print(country)
    print(sub_dict)
    
    for year,value in sub_dict.items():
        print(year,value)

Upvotes: 0

Related Questions