简体   繁体   中英

Adding key for average values in nested dictionary lists

I have a dictionary of keys of dates. Each date has a key:value pair of a project and a list of days.

I would like to add an average metric to each date key, while removing outliers above 6. My code is close, but produces some screwy results.

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

Expected Output:

{'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

output

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

the problem is dictionary cannot be updated while iterating through it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM