如何将包含多个值的列表转换为仅包含2个值的字典?

时间:2018-05-17 16:15:10

标签: python python-3.x

我有一个名为country_population的列表,如下所示:

[
  'Guam',
  {'total_population': {'date': '2013-01-01', 'population': 163943}},
  'Central%20African%20Republic',
  {'total_population': {'date': '2013-01-01', 'population': 4665025}}
]

我试过dict(country_population)

这给了我以下错误:

ValueError: dictionary update sequence element #0 has length 4; 2 is required

据我所知,我的列表中有4个值,但是如何将其转换为仅包含2个值的字典? 我想要一个看起来像这样的结果:

country_population = {'Guam' : '163943, 'Central%20African%20Republic' : 
'4665025' } 

3 个答案:

答案 0 :(得分:1)

使用dict()zip

<强>演示:

country_population = ['Guam', {'total_population': {'date': '2013-01-01', 'population': 163943}}, 'Central%20African%20Republic', {'total_population': {'date': '2013-01-01', 'population': 4665025}}]
print(dict((i[0], i[1]['total_population']["population"])for i in zip(country_population[0::2], country_population[1::2])))

<强>输出:

{'Central%20African%20Republic': 4665025, 'Guam': 163943}

答案 1 :(得分:1)

您可以尝试:

my_list = ['Guam', {'total_population': {'date': '2013-01-01', 'population': 163943}}, 'Central%20African%20Republic', {'total_population': {'date': '2013-01-01', 'population': 4665025}}]
# dictionary to store new results
result = {}

for i in range(0, len(my_list), 2):
    result[my_list[i]] = my_list[i+1]['total_population']['population']

print(result)

结果:

{'Central%20African%20Republic': 4665025, 'Guam': 163943}

对于使用dictionary comprehension的上述代码,您可以尝试:

result = {my_list[i] : my_list[i+1]['total_population']['population'] 
                                                for i in range(0, len(my_list), 2)}

答案 2 :(得分:0)

您描述的结果无效,因为它有多个名为NamePopulation的键。我认为你想要的是Name作为键,Population是值,你可以通过以2为增量跳过列表并将每对添加到dict中来做。

d=dict()
for i in range(len(country_population)/2):
    d[country_population[2*i]] = 
        country_population[2*i+1]['total_population']['population']

d['Guam']的结果将是163943。