dictionary - adding up the values(list) in a dictionary based on conditions

Viewed 53

How can I calculate the total of values(list) for each key in the dictionary in the function given below?

I want to write a python function called:

total_country_population(country_pop_dict, country_name)

Parameters:

  • country_pop_dict is a dictionary containing countries and their populations over a period of time.
  • country_name is the name of the country.

The function returns the total population of the parameter country in the dictionary.

An example of the function being called:

Given a dictionary named pop_dict:

pop_dict = {'Country_1':[10000, 20000, 30000, 40000],
            'Country_2': [6000, 7000, 8000],
            'Country_3':[65000] :}
print(total_country_population(pop_dict, 'Country_1'))
print(total_country_population(pop_dict, 'Country_2'))
print(total_country_population(pop_dict, 'Country_3'))

Expected result/output:

100000 #(10000 + 20000 + 30000 + 40000)
21000
65000
2 Answers
def total_country_population(country_pop_dict, country_name):
    return sum(country_pop_dict[country_name])

Is what you are looking for? The population over time for each country is saved in a list, so you sum the given list and return the result.

You can do this without a function as well:

for populations in pop_dict.values():
    print(sum(populations))
Related