首页 > 解决方案 > 如何将具有多个值的列表转换为只有 2 个值的字典?

问题描述

我有一个名为 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' } 

标签: pythonpython-3.x

解决方案


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

推荐阅读