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

  arrays, json, python

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]
    ]
}

Source: Python Questions

LEAVE A COMMENT