Reputation: 41
I have a Json file and was able to extract some values from it and sum them up. I want to be able to put the result to the right key but can't figure it out. Below is my code:
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)
So this is what I wanted to do, the result which is a1 will be placed a dictionary this way =>[ {'region A':{'constituency A':{'PARTY D': 1360, 'PARTY C': 1320, 'PARTY B': 1280, 'PARTY A': 340}}}]
When vote for constituency B in region A is also calculated, the result will be added to region A with constituency B as the key.
Upvotes: 0
Views: 52
Reputation: 404
I've iterated over each dict and counted the party votes for each constituency.
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},
},
}
}
]
}
data = fake['transaction'][0]
total_result = {}
for region, constituencies in data.items():
total_result[region] = {}
for constituency, stations in constituencies.items():
party_votes = {}
for station, parties in stations.items():
for party, vote in parties.items():
party_votes[party] = party_votes.get(party, 0) + vote
total_result[region][constituency] = party_votes
print(total_result)
prints
{'region A': {'constituency A': {'PARTY A': 340, 'PARTY B': 1280, 'PARTY C': 1320, 'PARTY D': 1360}}}
Upvotes: 1