如何管理包含三个项目的python字典并添加最后一个?

时间:2011-08-08 01:03:33

标签: python dictionary

我在python中有这样的字典:

x = {country:{city:population}:......}

我想创建一个像y = {country:cities_population}这样的新词典,其中cities_population会添加每个国家/地区的所有人口,我真的不知道该怎么做。

我试过了:

for country in x:
 for city, population in x[country].iteritems():
  if not country in y:
   y[country] = {}
  y[country] += population

我检查一个只有一个键和一个值的字典,但我不明白如何管理一个三项词典...请帮帮我!!!! :)

4 个答案:

答案 0 :(得分:2)

那么,怎么样:

 y = {  }
 for country, cities in x.iteritems():
     y[country] = sum(cities.values())

答案 1 :(得分:1)

我假设你想要总结的不仅仅是每个国家的城市人口:

>>> 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}}

答案 2 :(得分:0)

如下:

for country in x:
    total_population = 0
    for city, population in x[country].iteritems():
        total_population += population
    y[country] = total_population

答案 3 :(得分:0)

你想要的是一个新词典,其键是原始词,其值是当前值词典中值的总和

y = dict((c[0], sum(c[1].values())) for c in x.iteritems())