Home > Mobile >  Is there a way loop through each json array column one by one in python?
Is there a way loop through each json array column one by one in python?

Time:09-16

Okay, I recently just got help with the candidates and calculating the number of votes to match with every candidates' id. The problem I'm having now is that I want to loop through each json array column one by one to represent 1st choice, 2nd choice and so on. So it there a way to loop each json array column, represent it as a round, while calulate the votes to match each candidate for each round.

main.py

import json
import collections 
import numpy as np


with open('data.json', 'r') as f:
  db = json.load(f)
# prepare a temporary structure with all the candidates info   initialize number of votes
candidates_dict = {}
for candidate in db["candidates"]:
  candidates_dict[candidate["id"]] = {"name": candidate["name"], "num_votes": 0}

# loop on votes lists and count votes for all candidates
for votes in db["votes"]: 
  for candidate_id in votes:
        candidates_dict[candidate_id]["num_votes"]  = 1

# just print how many votes each candidate has done
for candidate_id, candidate_info in candidates_dict.items():
    print ("Candidate {} has {} votes".format(candidate_info["name"], candidate_info["num_votes"]))

data.json

{
  "candidates": [
  {
    "id": 1,
    "name": "Stan",
    "status": true
  },
  {
    "id": 2,
    "name": "Avia",
    "status": true
  },
  {
    "id": 3,
    "name": "Bob",
    "status": true
  }
  ],
  "votes": [
        [1, 2, 3],
        [2, 1, 3],
        [1],
        [2, 3],
        [3, 1],
        [3, 2, 1]
    ]
}

CodePudding user response:

Is it what you want ?

data = {
  "candidates": [
  {
    "id": 1,
    "name": "Stan",
    "status": True
  },
  {
    "id": 2,
    "name": "Avia",
    "status": True
  },
  {
    "id": 3,
    "name": "Bob",
    "status": True
  }
  ],
  "votes": [
        [1, 2, 3],
        [2, 1, 3],
        [1],
        [2, 3],
        [3, 1],
        [3, 2, 1]
    ]
}

from itertools import zip_longest

votes_columns = data["votes"]
for rank, *votes in zip_longest(range(3), *votes_columns):
    print(f"for rank {rank}, votes are {votes}")
for rank 0, votes are [1, 2, 1, 2, 3, 3]
for rank 1, votes are [2, 1, None, 3, 1, 2]
for rank 2, votes are [3, 3, None, None, None, 1]

CodePudding user response:

from what i understood i made this

for votes in db["votes"]: 
    for round_, candidate_id in enumerate(votes):
        candidates_dict[candidate_id]["num_votes"]  = 1
        if 'rounds' not in candidates_dict[candidate_id]:
            candidates_dict[candidate_id]['rounds'] = {1:0, 2:0, 3:0}
        candidates_dict[candidate_id]['rounds'][round_ 1]  = 1
        
for c_id, c_dict in candidates_dict.items():
    print(c_id, c_dict['rounds'])

>>>1 {1: 2, 2: 2, 3: 1}
>>>2 {1: 2, 2: 2, 3: 0}
>>>3 {1: 2, 2: 1, 3: 2}

but i see you import numpy so maybe you want to check this question: Convert Python sequence to NumPy array, filling missing values

this will help you get your data "in columns" in different ways

  • Related