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

时间:2015-04-27 15:58:35

标签: python python-2.7 dictionary list-comprehension 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 }

1 个答案:

答案 0 :(得分:1)

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

问题是字典在迭代时无法更新。