How to manage a python dictionary with three items and add the last one?
I have a dictionary in python like this:
x = {country:{city:population}:......}
and I want to create a new dictionary like y = {country:cities_population}, where cities_population adds all the population in every city in every country and I really don't know how to do it.
I tried this:
for country in x:
for city, population in x[country].iteritems():
if not country in y:
y[country] = {}
y[countr开发者_JAVA技巧y] += population
I check for a dictionary with only one key and one value but I don't understand how to manage a three items dictionary... help me please!!!! :)
Well, how about:
y = { }
for country, cities in x.iteritems():
y[country] = sum(cities.values())
I'm going to assume you want to sum up more than just the city populations for each country:
>>> attributes = ['population', 'gdp', 'murders']
>>> x = {'usa': {'chicago': dict(zip(attributes, [10, 100, 1000])), 'nyc':dict(zip(attributes, [20, 200, 2000]))}, 'china': {'shanghai': dict(zip(attributes, [9, 90, 900])), 'nagasaki': dict(zip(attributes, [2, 20, 200]))}}
>>> x
{'china': {'shanghai': {'gdp': 90, 'murders': 900, 'population': 9}, 'nagasaki': {'gdp': 20, 'murders': 200, 'population': 2}}, 'usa': {'nyc': {'gdp': 200, 'murders': 2000, 'population': 20}, 'chicago': {'gdp': 100, 'murders': 1000, 'population': 10}}}
>>> for country, cities in x.iteritems():
y[country] = {attr:0 for attr in attributes}
for city, attributes in cities.iteritems():
for attribute, value in attributes.iteritems():
y[country][attribute] += value
>>> y
{'china': {'gdp': 110, 'murders': 1100, 'population': 11}, 'usa': {'gdp': 300, 'murders': 3000, 'population': 30}}
How about something like:
for country in x:
total_population = 0
for city, population in x[country].iteritems():
total_population += population
y[country] = total_population
What you want is a new dictionary whose key is the original key and whose value is the sum of the values in the current value-dictionary.
y = dict((c[0], sum(c[1].values())) for c in x.iteritems())
精彩评论