每次迭代而不是整体更新字典

时间:2018-07-24 22:45:27

标签: python python-3.x

我在元组中的每个项目上都附加了一个字典,而且我遇到了一个问题,那就是字典要合计添加,而不是每个字典都单独计数。请参阅下面的代码:

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.

我当前的结果:

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})})

1 个答案:

答案 0 :(得分:2)

scores[color]对每种颜色引用相同的字典nps_categories。而是创建一个唯一的副本

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