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

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

最佳答案

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

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

关于python - 每次迭代更新字典,而不是整体更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51508555/

相关文章:

python - 如何在 Python 中指定(什么)的方法返回类型列表?

python-3.x - 将字典浮点值四舍五入到小数点后两位 : Python

python - 如何在字典值是列表项上使用计数器

python - 我有一组不等长的列表,计算每个列表长度的最快方法是什么

python - 在辅助监视器中打开 pygame 全屏窗口

python - pandas dataframe 删除频率较低的行

python - 在某些字符之后分割字符串?

python - 使用索引查找带连字符的单词

python - 为什么角色类和animation_dir上有一个AttributeError报告,尽管它已经明确定义了?

python 3 : apply an operator over an iterable