Reputation: 9243
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 }
Upvotes: 1
Views: 238
Reputation: 9044
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.
Upvotes: 1