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

Python: JSON, Problem with list of dictionaries, certain value into my dictionary

So, I have been thinking of this for a long time now, but can’t seem to get it right. So I have to use a JSON file to make a dictionary where I get the keys: ‘userIds’ and the value ‘completed’ tasks in a dictionary. The best I got was the answer: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 90}, with this code under:

import requests


response1 = requests.get("https://jsonplaceholder.typicode.com/todos")
data1 = response1.json()

dict1 = {}
keys = []
values = []

for user in data1:
    if user not in keys or values:
        keys.append(user['userId'])
        values.append(0)


for key, value in zip(keys, values):
    dict1[key] = value



for user in data1:
    if user['completed'] == True:
        dict1[key] += 1



print(dict1)


but I feel like this next code would be closer, but I can’t figure out how to get it to work


import requests

response1 = requests.get("https://jsonplaceholder.typicode.com/todos")
data1 = response1.json()

dict1 = {}
keys = []
values = []

for user in data1:
    if user not in keys or values:
        keys.append(user['userId'])
        values.append(0)


for key, value in zip(keys, values):
    dict1[key] = value


for key, value in data1.items():
    if user['completed'] == True:
        dict1[key].update += 1


print(dict1)

After this, the output is just
" line 24, in
for key, value in data1.items():
AttributeError: ‘list’ object has no attribute ‘items’",

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

And I do get why, I don’t jsut know how to continue from here.

Would really appreciate anyones help, with this obnoxious task.

>Solution :

can u try this ?

import requests

response1 = requests.get("https://jsonplaceholder.typicode.com/todos")
data1 = response1.json()

dict1 = {}
keys = []
values = []

for user in data1:
    if user not in keys or values:
        keys.append(user['userId'])
        values.append(0)


for key, value in zip(keys, values):
    dict1[key] = value

print(data1)
for x in data1:
    for key, value in x.items():

        if key =="completed" :
            if value == True:
                dict1[x["userId"]] += 1


print(dict1)
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