Neemaximo
Neemaximo

Reputation: 20821

Update dictionary per iteration, and not overall

I have a dictionary attached to each item in a tuple, and I am having an issue where the dictionaries are adding as a total, instead of each dictionary counting separately. See below for my code:

nps_user_ranges_default = {
    'promoters': [9, 10],
    'passive': [7, 8],
    'detractors': [1, 2, 3, 4, 5, 6],
    'skipped': [-1]
}

data = [(1, 'blue'), (10, 'blue'), (9, 'blue'), (10, 'blue'),
            (4, 'green'), (10, 'green'), (6, 'red'), (10, 'red'), (10, 'green')]

nps_categories = {
            'promoters': 0,
            'detractors': 0,
            'passive': 0,
            'skipped': 0
        }

scores = defaultdict(dict)      
for score, color in data:
    scores.setdefault(color, []).append(score)

for color, score in scores.items():
    scores[color] = (score, nps_categories)

for color, score in scores.items():
    sc, nps_category = score[0], score[1]
    for s in sc:
        if s in nps_user_ranges_default['promoters']:
            nps_category['promoters'] += 1
        elif s in nps_user_ranges_default['detractors']:
            nps_category['detractors'] += 1
        elif s in nps_user_ranges_default['passive']:
            nps_category['passive'] += 1
        else:
            nps_category['skipped'] += 1    

print(scores) 
# The issue I am seeing here is that all dictionaries are adding on top of each other.
# I can't seem to get it so they all operate separately.

My current result:

defaultdict(<type 'dict'>, {'blue': ([1, 10, 9, 10], {'promoters': 6, 'passive': 0, 'skipped': 0, 'detractors': 3}), 'green': ([4, 10, 10], {'promoters': 6, 'passive': 0, 'skipped': 0, 'detractors': 3}), 'red': ([6, 10], {'promoters': 6, 'passive': 0, 'skipped': 0, 'detractors': 3})})

Upvotes: 1

Views: 39

Answers (1)

Sunitha
Sunitha

Reputation: 12015

scores[color] reference the same dict nps_categories for each color. Create a unique copy instead

for color, score in scores.items():
    scores[color] = (score, nps_categories.copy())

Upvotes: 2

Related Questions