无法更新python词典中的输出

时间:2019-02-01 10:19:38

标签: python dictionary

我在test.csv文件中具有以下格式的输出

/,9.8G,6.8G,27%
/home,4.8G,3.6G,22%
/opt,9.8G,5.2G,44%
/tmp,3.9G,3.6G,2%

我正在从test.csv文件读取输入并转换为字典。

import csv
output1={}
output2={}
with open('test.csv', mode='r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for row in csv_reader:
        Mounted = row[0]
        Total = row[1]
        used = row [3]
        available = row[2]
        st = {}.fromkeys(['Mount'],Mounted)
        st1 = {}.fromkeys(['Total'],Total)
        st2 = {}.fromkeys(['used'],used)
        st3 = {}.fromkeys(['available'],available)
        st = dict(st.items() + st1.items() + st2.items() + st3.items())
        output1.update(st)
        print  'output1 = ',output1

output2["DiskStatus"] = output1
print output2

以以下格式接收输出

output1 =  {'available': '6.8G', 'used': '27%', 'Mount': '/', 'Total': '9.8G'}
output1 =  {'available': '3.6G', 'used': '22%', 'Mount': '/home', 'Total': '4.8G'}
output1 =  {'available': '5.2G', 'used': '44%', 'Mount': '/opt', 'Total': '9.8G'}
output1 =  {'available': '3.6G', 'used': '2%', 'Mount': '/tmp', 'Total': '3.9G'}

{'DiskStatus': {'available': '19G', 'used': '1%', 'Mount': '/log', 'Total': '20G'}}

我期望以以下格式输出。请对此提供帮助。

output1 =  {'available': '6.8G', 'used': '27%', 'Mount': '/', 'Total': '9.8G'},{'available': '3.6G', 'used': '22%', 'Mount': '/home', 'Total': '4.8G'},{'available': '5.2G', 'used': '44%', 'Mount': '/opt', 'Total': '9.8G'},{'available': '3.6G', 'used': '2%', 'Mount': '/tmp', 'Total': '3.9G'}

{'DiskStatus': [{'available': '19G', 'used': '1%', 'Mount': '/log', 'Total': '20G'},{'available': '3.6G', 'used': '22%', 'Mount': '/home', 'Total': '4.8G'},{'available': '5.2G', 'used': '44%', 'Mount': '/opt', 'Total': '9.8G'},{'available': '3.6G', 'used': '2%', 'Mount': '/tmp', 'Total': '3.9G'}]}

1 个答案:

答案 0 :(得分:1)

看起来您需要词典列表。

例如:

import csv
disk_status = {'DiskStatus': []}
header = ['Mount', 'Total', 'available', 'used']
with open('test.csv') as infile:
    reader = csv.reader(infile)
    for line in reader:
        disk_status["DiskStatus"].append(dict(zip(header, line)))
print(disk_status)

输出:

{'DiskStatus': [{'Mount': '/',
                 'Total': '9.8G',
                 'available': '6.8G',
                 'used': '27%'},
                {'Mount': '/home',
                 'Total': '4.8G',
                 'available': '3.6G',
                 'used': '22%'},
                {'Mount': '/opt',
                 'Total': '9.8G',
                 'available': '5.2G',
                 'used': '44%'},
                {'Mount': '/tmp',
                 'Total': '3.9G',
                 'available': '3.6G',
                 'used': '2%'}]}