根据键

时间:2015-07-23 17:13:19

标签: python list dictionary iteration average

列出包含以下示例的n - 字典:

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
]

我试图将它们平均化,逐出每个字典,然后使用函数的每个键:

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
    }
    for key_dict in data:
        for key, val in key_dict.iteritems():
            value= float(val)
            avg[key] = sum( float(avg[key]) + float(value)) / len(data)
    return avg  

我看到它无法跨浮点值迭代的错误。

TypeError: 'float' object is not iterable

我很困惑这是如何发生以及如何解决这个问题并使代码正常工作。

1 个答案:

答案 0 :(得分:3)

您正试图在 sum()值上使用float

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

这不会像sum()一样工作,希望你给它一个序列。您不需要使用sum()来添加两个float值,+就足够了。

你无法计算那样的平均值;你需要先将所有值相加,而不是单独划分长度:

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