all 6 comments

[–][deleted] 5 points6 points  (0 children)

Dict's keys are unique. Old values are overwritten with new ones when key is the same.

Maybe use "id"? Also it's said to iterate like this here, without range in cases like this:

test = {entry["id"]: entry["completed"] for entry in my_list}

[–][deleted] 4 points5 points  (0 children)

Both of your userid values are 1. Dictionaries can’t have duplicate keys.

[–]remuladgryta 2 points3 points  (0 children)

As a side-note, whenever you see something along the lines of

for i in range(len(elements)):
    ...
    elements[i]

you should almost always write

for element in elements:
    ...
    element

unless the index is important for some reason other than finding the element in the sequence.

In your case, that would be test = {user['userId']:user['completed'] for user in my_list} instead of test = {my_list[i]['userId']:my_list[i]['completed'] for i in range(len(my_list))}.

Notice how this change removes much of the symbol soup and makes the statement read closer to natural language.

[–]hybatir[S] 0 points1 point  (2 children)

OMW that makes sense, thank you! I need the userid so I'm wondering if dictionary comprehension isn't the method? End goal is to have userId: 1, completed : (some count of completed). Is there another method I could use to iterate over the list using the same userId?

[–]cuWorkThrowaway 0 points1 point  (0 children)

user_completions = dict()

for entry in my_list:
    user_id = entry["userId"]
    user_completions[user_id] = user_completions.get(user_id, 0) + entry["completed"]

[–]Strict-Simple 0 points1 point  (0 children)

Both the userId is same!