我试图按标题中的顺序打印输出,但仍然无法接收到无序的输出。请对此提供帮助。
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%
代码
import csv
from collections import OrderedDict
import collections
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(collections.OrderedDict(dict(zip(header, line))))
print(disk_status)
输出
{'DiskStatus': [{'available': '6.8G', 'Mount': '/', 'Total': '9.8G', 'used': '27%'}, {'available': '3.6G', 'Mount': '/home', 'Total': '4.8G', 'used': '22%'}, {'available': '5.2G', 'Mount': '/opt', 'Total': '9.8G', 'used': '44%'}, {'available': '3.6G', 'Mount': '/tmp', 'Total': '3.9G', 'used': '2%'}]}
预期结果
{'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%'}]}
答案 0 :(得分:1)
只需不创建AuthorNo
--------
1
2
4
5
,只需将dict
的结果传递给zip
:
collections.OrderedDict
Python 3.7及更高版本不需要此功能,因为3.7 disk_status["DiskStatus"].append(collections.OrderedDict(zip(header, line)))
保持插入元素(https://docs.python.org/3/whatsnew/3.7.html)的顺序
答案 1 :(得分:0)
请勿在{{1}}内创建字典。 更新的代码将是
OrderedDict
输出:
import csv
from collections import OrderedDict
import collections
disk_status = {'DiskStatus': []}
header = ['Mount', 'Total', 'available', 'used']
with open('test.csv') as infile:
reader = csv.reader(infile)
for line in reader:
#updated line
disk_status["DiskStatus"].append(collections.OrderedDict(zip(header, line)))
print(disk_status)