How to update json object in a loop?

Question:

My end goal is to have a json file in a variable that can be passed to an API. Right now, I can’t get the JSON to update how I want it to in the loop. How can I get it to output/append all the options and not just the last in the loop?

import json

info = {}

states = ["MN", "AZ", "IL"]
cities = ["One", "Two", "Three"]
votes = ["No", "Yes", "Maybe"]

for state in states:
    for city in cities:
        for vote in votes:
            info.update({'name': 'master', 'state': state, 'cities': {'name': city, 'votes': {'decision': vote}}})

print(json.dumps(info, indent=4))

And the output I’m getting is:

{
    "name": "master",
    "state": "IL",
    "cities": {
        "name": "Three",
        "votes": {
            "decision": "Maybe"
        }
    }
}

But I want it to be:

{

    "name": "master",
         {
            "state": "MN",
            "cities": {
                 "name": "One",
                 "votes": {
                            "decision": "No"
                          }
        },
        {
            "state": "MN",
            "cities": {
                 "name": "One",
                 "votes": {
                            "decision": "Yes"
                          }
        }
        
        ....etc.....
    }
}

edit: updated desired output

Asked By: H14

||

Answers:

You need to put all the state information into a list. Then you can simply append each dictionary to that list. There’s nothing to update, since each dictionary is a separate element of the list

import json

info = {
    "name": "master",
    "states": []
}

states = ["MN", "AZ", "IL"]
cities = ["One", "Two", "Three"]
votes = ["No", "Yes", "Maybe"]

for state in states:
    for city in cities:
        for vote in votes:
            info['states'].append({
                "state": state,
                "cities": {
                    "name": city,
                    "votes": { "decision": vote }
                }
            });

print(json.dumps(info, indent=4))

DEMO

I wonder, though, if this is really the result you want. You have a key called cities; the name suggests that it should contain more than one city, but it only contains one — you have each city in a separate state dictionary. The same thing goes for votes — it’s just one vote, not all of the votes for that city.

Answered By: Barmar
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.