From the data at https://jsonplaceholder.typicode.com/todos I wanted to count "completed" items by user.
Currently, I approach this by first collecting the existing user Id keys, then for each element in the dataset check if its owned by the current user and append to the list of items of that user.
users_items = {}
import json
from urllib import request
# Data from
uri = "https://jsonplaceholder.typicode.com/todos"
response = request.urlopen(uri).read()
data = json.loads(response)
def get_user_ids(items):
for item in items:
users_items[item['userId']] = None
def get_user_items():
for uid in users_items:
items = []
for item in data:
if(item['userId'] == uid):
items.append(item['completed'])
users_items[uid] = items
done_items_by_user = {}
def count_completed_by_user():
for user in users_items:
done_items_by_user[user] = sum(users_items[user])
get_user_ids(data)
get_user_items()
I especially don't like the double loop and the initialization of the dictionary values with an empty list in get_users_ids.
item['completed']is a boolean value. Are you sure that you need to accumulate only boolean values?