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:
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)