SudoGaron
SudoGaron

Reputation: 438

Python Counter() adding value to existing keys

developer_base = Counter({
        'user1': {'XS': 0, 'S': 0, 'M': 0, 'L': 0, 'XL': 0},
        'user2': {'XS': 0, 'S': 0, 'M': 0, 'L': 0, 'XL': 0},
        'user3': {'XS': 0, 'S': 0, 'M': 0, 'L': 0, 'XL': 0},
        'user4': {'XS': 0, 'S': 0, 'M': 0, 'L': 0, 'XL': 0},
    })

Loop to gather Counter data:

for y in time_list:
                story_size = models.get_specific_story(y['story_id'])
                if story_size is not "?":
                    counts = Counter(y['minutes_spent'])
                    print(counts)
                    developer_base = developer_base + counts

Should Counterbe part of a for loop? story_size always equals one of the keys in the nested dict (S,XS,M etc). time_list has the ['minutes_spent'] which is the value that needs to add into the dictionary. the problem seems to be that time_list has a nested dict which is ['user']['first_name'] and it is equal to the developer_base keys for user1 through user4.

So I need to add up all the 'minutes_spent' in time_list for each user.

Update: JSON data

[{'project_slug': 'test', 'project_id': 19855, 'date': '2016-02-11', 'task_name': None, 'iteration_name': 'test', 'notes': '', 'user_id': 81946, 'story_id': 392435, 'iteration_id': 76693, 'story_name': 'test', 'user': {'id': 81946, 'last_name': 'test', 'first_name': 'user1', 'email': 'test', 'username': 'test'}, 'project_name': 'Development', 'id': 38231, 'minutes_spent': 240}]

The data is much larger but this is one whole section.

Upvotes: 0

Views: 2713

Answers (1)

phihag
phihag

Reputation: 287825

In the first snippet, you are abusing Counter. That snippet only works due to quirks in Python 2, where one can compare dicts. The values of a counter are supposed to be numbers.

Similarly, y['minutes_spent'] is an integer, and Counter(y['minutes_spent']) will just throw an error. In addition, story_size is not "?" does not do what you expect.

Assuming the real problem is

add up all the 'minutes_spent' in time_list for each user.

then you can use a Counter:

from collections import Counter
c = Counter()
for y in time_list:
    c[y['user']['id']] += y['minutes_spent']

Upvotes: 2

Related Questions