在嵌套字典列表中为平均值添加键

Adding key for average values in nested dictionary lists

我有一本日期键字典。每个日期都有 key:value 对项目和日期列表。

我想为每个日期键添加一个平均指标,同时删除 6 以上的异常值。我的代码很接近,但产生了一些奇怪的结果。

import numpy as np
d = {}
d['1/2/15'] = {'Project 1' : [1,4,7], 'Project 2' : [1,5, 11]}

for key, value in d.iteritems():
    avg =  np.mean([x for x in d[key]['Project 1'] if x < 6])
    d[key][str(value) + ' Average'] = avg

print d

预期输出:

{'Project 1' : [1,4,7], 'Project 1 Average' : 2.5, 'Project 2' : [1,5,7], 'Project 2 Average' : 3.0 }
import numpy as np
d = {}
d['1/2/15'] = {'Project 1' : [1,4,7], 'Project 2' : [1,5, 11]}

for key, value in d.iteritems():
        d_avg = {}
        for k, v in value.iteritems():
            avg =  np.mean([x for x in d[key][k] if x < 6])
            d_avg[str(k) + ' Average'] = avg
        d[key].update(d_avg)

print d

输出

{'1/2/15': {'Project 2 Average': 3.0, 'Project 2': [1, 5, 11], 'Project 1 Average': 2.5, 'Project 1': [1, 4, 7]}}

问题是字典在遍历时无法更新。