python - Average a list of dictionaries based on key -


having list of n - dictionaries sample below:

n = [   {'gb_written': '6.63',   'avg_write_put': '81.45',   'bgb_written': '4.78',   'bbytes_written': '5129101312',   'body_len': '512',   'body_len_dist': '32',   'bytes_written': '7118499840',   'cache_size': '2.00',   'device': 1,   'documents': '1000000',   'duration': '60',   'engine': 2,   'key_len': '32',   'key_len_dist': '2',   'read_ops': '31287.45',   'read_us': '31.96',   'reads': '1879063',   'thread_reader': '1',   'thread_writer': '1',   'total_ops': '2885853',   'write_amp': '9.4',   'write_ops': '16763.61',   'write_us': '59.65',   'writes': '1006790',   'written_perdoc': '4.97'},   # more dictionaries ] 

i trying average them out iterating out each dictionary, each key function:

def prepare_data(data):     avg  = {         'engine' : 0,         'device' : 0,         'documents' : 0,         'thread_reader': 0,         'thread_writer' : 0,         'cache_size' : 0,         'key_len' : 0,         'key_len_dist' : 0,         'body_len' : 0,         'body_len_dist' : 0,         'duration' : 0,         'reads' : 0,         'read_ops' : 0,         'read_us' : 0,         'writes' : 0,         'write_ops' : 0,         'write_us' : 0,         'total_ops' : 0,         'bytes_written' : 0,         'gb_written' : 0,         'bbytes_written' : 0,         'bgb_written' : 0,         'avg_write_put' : 0,         'written_perdoc' : 0,         'write_amp' : 0     }     key_dict in data:         key, val in key_dict.iteritems():             value= float(val)             avg[key] = sum( float(avg[key]) + float(value)) / len(data)     return avg   

i seeing error can not iterate across float value.

typeerror: 'float' object not iterable 

i confused how happening , how fix issue , code working.

you trying use sum() on single float value:

sum( float(avg[key]) + float(value)) 

that won't work sum() expects give sequence. don't need use sum() add 2 float values, + enough that.

you cannot calculate average that; need first sum all values, in separate step divide length:

for key_dict in data:     key, val in key_dict.iteritems():         avg[key] += float(val) return {key: value / len(data) key, value in avg.iteritems()}     

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -