如何在 python 字典中按顺序打印输出

How to print the output in order in python dictionary

我尝试按 header 中提到的顺序打印输出,但我仍然收到无序的输出。请帮忙解决这个问题。

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%'}]}

只是不要创建 dict,只需将 zip 结果传递给 collections.OrderedDict:

disk_status["DiskStatus"].append(collections.OrderedDict(zip(header, line)))

Python 3.7 及更高版本不需要这样做,因为 3.7 dict 保持插入元素的顺序 (https://docs.python.org/3/whatsnew/3.7.html)

不要在 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)

输出:

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