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

Extracting chosen key:value pairs from a json output

Beginner here for sure.
I try to get a list of dicts with chosen key-value pairs from a json output but I am stuck for now.

json:

d = [{'type': 'pages', 'dates': [{'date': '2021-12-01,2021-12-31', 'items': [{'value': '810', 'value_percent': '42.2', 'title': 'Cat', 'stats_url': 'http://clicky.com/stats/visitors?site_id=100', 'url': 'http://acqui.it/cat'}, {'value': '303', 'value_percent': '15.8', 'title': 'Viag title', 'stats_url': 'http://clicky.com/stats/visitors?site_id=1009', 'url': 'http://acq.it/dfgdf'}]}]}]

I tried:

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

list_new = []

for k in d:
    dict_1 = {}
    dict_1['url'] = k['dates'][0]['items'][0]['url']
    dict_1['ruch'] = k['dates'][0]['items'][0]['value']
    list_new.append(dict_1)

print(list_new)

Current output:


[{'url': 'http://acqui.it/cat', 'ruch': '810'}]

Expected output:


[{'url': 'http://acqui.it/cat', 'ruch': '810'},
{'url': 'http://acq.it/dfgdf', 'ruch': '303'}]

>Solution :

for k in d iterates through the top level of the JSON, which is a list of length 1. I believe what you’re trying to do is:

for k in d[0]["dates"][0]["items"]:
    dict_1 = {}
    dict_1["url"] = k["url"]
    dict_1["ruch"] = k["value"]
    list_new.append(dict_1)
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