0

Question

My Python app needs to generate a JSON file that will be consumed by React. The Python app generates lists similar to the following:

animals = ["dog","cat","fish"]
count = [3,6,1]

What have I tried

I can dump this to JSON using zip and a dict:

json.dumps(dict(zip(animals,count)))

'{"dog": 3, "cat": 6, "fish": 1}'

Desired output

I would like the JSON to look like this:

'[{"name":"dog","count":3},{"name":"cat","count":6},{"name":"fish","count":1}]'

What is the most Pythonic way of doing this?

halfer
  • 19,824
  • 17
  • 99
  • 186
nipy
  • 5,138
  • 5
  • 31
  • 72
  • 1
    I am not sure there is a "pythonic" way of doing this, but more of just a programmatic way. What you need is to iterate through those 2 arrays (or at least one of them), and create your animal objects to be appended to your final array. [Iterate arrays](https://stackoverflow.com/questions/51919448/iterating-over-arrays-in-python-3) | [Create list of objects](https://stackoverflow.com/questions/348196/creating-a-list-of-objects-in-python/348215). I am not a python guru, so others may have actual pythonic abilities beyond me :) – segFault Mar 15 '20 at 12:18
  • Do you want your json to be a single object of only the first animal and count or do you want a json array containing 3 objects each containing an animal name and count? – steviestickman Mar 15 '20 at 13:30
  • @steviestickman please see updated desired output – nipy Mar 15 '20 at 16:22

2 Answers2

1

it looks like your question has two parts: How to represent an animal population in json and how to represent a group of animal populations in json. the json module can convert some python data structures to json data structures.

you can represent an animal population as a dict containing a name and a count.

then you need to construct a list that contains an animal population for each type of animal.

animal_names = ["dog", "cat", "fish"]
animal_counts = [3, 6, 1]


def animal_population(name, count):
    """
    >>> animal_population('dog', 3)
    {'name': 'dog', 'count': 3}
    """
    return {
        'name': name,
        'count': count
    }


animals = [
    animal_population(name, count)
    for name, count in zip(animal_names, animal_counts)
]


if __name__ == "__main__":
    import json
    print(json.dumps(animals))

output:

[{"name": "dog", "count": 3}, {"name": "cat", "count": 6}, {"name": "fish", "count": 1}]
steviestickman
  • 1,132
  • 6
  • 17
1

I eventually came up with this which appears to be the simplest approach:

json.dumps([{'name': name, 'count': count} for name,count in zip(animals,count)])

Output:

'[{"name": "dog", "count": 3}, {"name": "cat", "count": 6}, {"name": "fish", "count": 1}]'
nipy
  • 5,138
  • 5
  • 31
  • 72