Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Save Python dictionary to the JSON format (adding names)

I filtered and processed some data and I got it in the following format:

{'2020-04-20': [('EUR', 34.02), ('USD', 30.18), ('AWG', 24.44), ('GPB', 20.68)], 
 '2020-04-25': [('EUR', 16.88), ('USD', 15.06), ('AWG', 12.17), ('GPB', 10.4)], 
 '2020-04-27': [('EUR', 17.14), ('GPB', 10.28), ('USD', 7.58), ('AWG', 5.06), ('CZK', 2.44)]
...
}

Now, I want to save it to the JSON format, which I think should look this way (I’m not sure if I write suitable format, because such a JSON, I want to send to Grafana and make some graphs):

json_data = {
  "filtered_data": [
    {
      "data": "2015-01-04",
      "currencies": {
        "EUR": 34.02,
        "USD": 30.18,
        "AWG": 24.44,
        "GPB": 20.68}
    },
    {
      "data": "2015-01-25",
      "currencies": {
        "EUR": 16.88,
        "USD": 15.06,
        "AWG": 12.17,
        "GPB": 10.4}
    },
    ...
  ]
}

I appreciate any hints, how to get such a valid JSON format.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

formatting your data is quite simple:

filtered_data = [{"data": k, "currencies": dict(v)} for k, v in data.items()]

the trick here is that your currency data is already in a perfect format to feed directly to dict

now all you have to do is

json.dumps({'filtered_data': filtered_data})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading