Python:在for循环中附加到字典

时间:2017-10-24 12:14:36

标签: python python-3.x dictionary

尝试使用Linux fio命令的输出填充dict时,我得到了意想不到的结果。

with open('normal_output.txt', 'rb') as f:
    for line in f.readlines():
        d = {}

        if ':' not in line:
            continue
        print("LINE: ", line)
        key, value = line.strip().split(':', 1)
        d[key] = value

我希望一本充满KVP的词典如下:

('KEY: ', 'READ')
('VALUE: ', ' io=131220KB, aggrb=13890KB/s, minb=13890KB/s, maxb=13890KB/s, mint=9447msec, maxt=9447msec')
('KEY: ', 'WRITE')
('VALUE: ', ' io=130924KB, aggrb=13858KB/s, minb=13858KB/s, maxb=13858KB/s, mint=9447msec, maxt=9447msec')
('KEY: ', 'Disk stats (read/write)')
('VALUE: ', '')
('KEY: ', 'sda')
('VALUE: ', ' ios=32642/32600, merge=0/12, ticks=7472/936, in_queue=8392, util=88.18%')
{'sda': ' ios=32642/32600, merge=0/12, ticks=7472/936, in_queue=8392, util=88.18%'}

但相反,我只是得到了最后一个KVP:

{'sda': ' ios=32642/32600, merge=0/12, ticks=7472/936, in_queue=8392, util=88.18%'}

我尝试了d [key] .append(value)但是这给了我:KeyError:'fio_test'

2 个答案:

答案 0 :(得分:4)

在你的循环中,你正在创建一个新的空字典d。将其移到for循环之外。

来自

with open('normal_output.txt', 'rb') as f:
    for line in f.readlines():
        d = {}
        # do work

with open('normal_output.txt', 'rb') as f:
    d = {}
    for line in f.readlines():
        # do work

您甚至可以在上下文管理器(with语句)之外移动字典创建,以保持逻辑更有条理,但这更多的是品味和风格。

答案 1 :(得分:2)

您正在for循环中实例化字典,因此每次循环时您都会覆盖字典。在for循环之外加上d = {}