Home > Software engineering >  How to update json object in a loop?
How to update json object in a loop?

Time:08-12

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

CodePudding user response:

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.

  • Related