Skip to content
Advertisement

Easiest way to split JSON file using Python

I am working on an interactive visualization of the world happiness report from the years 2015 up to 2020. The data was split into 6 csv files. Using pandas, I have succesfully cleaned the data and concatenated them into one big JSON file with the following format:

JavaScript

Now, I would like to programmatically format the JSON file such that it has the following format:

JavaScript

It has to be done programmatically, since there are over 900 distinct (country, year) pairs. I want the JSON in this format since it make the JSON file more readable, and makes it easier to select appropriate data. If I want the rank of Iceland in 2015, I can then do data[2015]["Iceland"]["Happiness Rank"]

Does anyone know the easiest / most convenient way to do this in Python?

Advertisement

Answer

If data is your original list of dictionaries:

JavaScript

Output:

JavaScript

This assumes that the dictionaries in data will already be grouped together by year.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement