2024-07-04 16:38:43 发布
网友
我有两本大字典: zip2state和zip2pop
两者都以邮政编码作为键,第一个以州缩写作为值,而另一个以该邮政编码中的人口作为值
例:
zip2pop {99628:104
我的任务是创建一个新的字典,对某个州的所有人口进行汇总,并将缩写作为键,以总人口作为值
我试过一些方法,但似乎都无法奏效,有什么帮助吗
编辑: 很抱歉,我搞错了这个例子,在zip2state中,有不同的邮政编码作为键,状态缩写作为值
zip2state {99628:'AK'
您可以遍历其中一个的键和另一个的值
state2pop = dict() for state, pop in zip2state.keys(), zip2pop.values(): state2pop[state] = pop
如果zip2state确实将zipcode作为键,那么可以用zip2state.values()替换zip2state.keys()
zip2state.values()
zip2state.keys()
考虑到这些示例输入,请尝试以下操作:
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}
您可以遍历其中一个的键和另一个的值
如果zip2state确实将zipcode作为键,那么可以用
zip2state.values()
替换zip2state.keys()
考虑到这些示例输入,请尝试以下操作:
收益率:
相关问题 更多 >
编程相关推荐