python - 如何将具有多个值的列表转换为只有 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' }
解决方案
使用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}
推荐阅读
- c# - 如何获取当前目录中的列表显示文件夹?
- spring - 当 spring Vault 更新令牌不起作用时重新启动 pod
- android - 单个片段中的多个 LiveData 观察者
- css - 媒体查询行为不准确
- react-native - @react-native-community/blur 模块是否正常工作
- layout - 浮动问题 | Clearfix 在我的个人博客上
- java - Java Regex:用相等数量的另一个字符替换两个特定字符之间的字符
- unix - 如何使用 Unix 命令从长文本短语中 grep 特定关键字?
- spring-boot - UnsatisfiedDependencyException,使用名称创建 bean 时出错
- mysql - MYSQL-如何知道数组中所有给定的ID(记录ID)是否已经在表中?