首页 > 解决方案 > 根据两个不同字典的键和值创建一个新字典

问题描述

我有两个大字典: zip2state 和 zip2pop

两者都以邮政编码作为键,第一个以州缩写作为值,而另一个以该邮政编码中的人口作为值。

前任:

zip2pop {99628 : 104 .....

我的任务是创建一个新字典,汇总某个州的所有人口,并以总人口为值,将缩写作为键

我已经尝试了一些东西,但似乎没有什么可以接近工作,有什么帮助吗?

编辑:对不起,我搞砸了这个例子,在 zip2state 中有不同的邮政编码作为键,状态缩写作为值

zip2state {99628:'AK',......

标签: pythonpython-3.xdictionary

解决方案


给定这些示例输入,请尝试以下操作:

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}

推荐阅读