python - 根据两个不同字典的键和值创建一个新字典
问题描述
我有两个大字典: zip2state 和 zip2pop
两者都以邮政编码作为键,第一个以州缩写作为值,而另一个以该邮政编码中的人口作为值。
前任:
zip2pop {99628 : 104 .....
我的任务是创建一个新字典,汇总某个州的所有人口,并以总人口为值,将缩写作为键
我已经尝试了一些东西,但似乎没有什么可以接近工作,有什么帮助吗?
编辑:对不起,我搞砸了这个例子,在 zip2state 中有不同的邮政编码作为键,状态缩写作为值
zip2state {99628:'AK',......
解决方案
给定这些示例输入,请尝试以下操作:
zip2pop = {99628: 104, 99629: 9242, 99638: 5524, 99618: 89, 99648: 6502}
zip2state = {99628: 'AK', 99629: 'AK', 99638: 'WA', 99618: 'WA', 99648: 'OR'}
state2pop = {}
for z, s in zip2state.items():
if s in state2pop:
state2pop[s] += zip2pop[z]
else:
state2pop[s] = zip2pop[z]
产量:
{'AK': 9346, 'WA': 5613, 'OR': 6502}
推荐阅读
- reactjs - 将 firebase Cloud Firestore 数据导出到项目中的其他文件
- python - python错误 - 无效参数:无法终止退出的进程
- r - 如何在案例具有未定义性别的情况下将变量设置为 0
- google-analytics - 如何在数据库中建模谷歌分析数据
- database - 这是否标准化到第三个 NF
- python - 使用字符串识别对象,python 3
- typescript - 错误:在“tsconfig”或“jsconfig”中设置“experimentalDecorators”选项以删除此警告
- php - 如何在 yii2 gridview 中根据条件隐藏列?
- azure-devops - 在 azure devops 中使用 azure powershell 内联任务获取 azure 功能键并将其放入 keyvault 的脚本
- java - Intellij 将私有字段及其访问器方法移动/重构到不同的类