【发布时间】:2022-01-20 09:37:06
【问题描述】:
我有一个 Json 文件,并且能够从中提取一些值并将它们汇总。我希望能够将结果放在正确的键上,但无法弄清楚。 以下是我的代码:
from builtins import print
import json
import jmespath
from collections import Counter
const = ['constituency A','constituency B','constituency C']
region = ['region A','region B','reigon C']
poll = ['POLLING STATION A','POLLING STATION B','POLLING STATION C','POLLING STATION Z','POLLING STATION F']
fake = {'transaction':[{'region A':{'constituency A':{
'POLLING STATION A':{'PARTY A':10,'PARTY B':20,'PARTY C':30,'PARTY D':40},
'POLLING STATION Z':{'PARTY A':50,'PARTY B':60,'PARTY C':70,'PARTY D':80},
'POLLING STATION B':{'PARTY A':90,'PARTY B':100,'PARTY C':110,'PARTY D':120},
'POLLING STATION F':{'PARTY A':190,'PARTY B':1100,'PARTY C':1110,'PARTY D':1120},},
}}]}
a = json.dumps((fake))
p = json.loads(a)
j = jmespath.search('transaction[*]',p)
ham = []
man = set()
for new_d in j:
for k,v in new_d.items():
for i_k,i_v in v.items():
for w,c in i_v.items():
if w in poll and i_k in const and k in region:
ham.append(c)
up = len(ham)
i= 0
a1=Counter()
while i < up:
a1 += Counter(ham[i])
i+=1
print(a1)
所以这就是我想要做的,结果是 a1 将被这样放置一个字典 =>[ {'region A':{'constituency A':{'PARTY D': 1360, 'PARTY C': 1320, 'PARTY B': 1280, 'PARTY A': 340}}}]
当同时计算A区选区B的投票时,结果会以选区B为key添加到A区。
【问题讨论】:
标签: python-3.x django