【问题标题】:How to print the output in order in python dictionary如何在python字典中按顺序打印输出
【发布时间】:2019-06-27 05:56:14
【问题描述】:

我尝试按标题中提到的顺序打印输出,但我仍然收到无序的输出。请帮忙。

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

【问题讨论】:

  • 它对我有用。我的python版本是3.6。

标签: python dictionary collections ordereddict


【解决方案1】:

只是不要创建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)

【讨论】:

  • 只是注意到 3.6 也保留了插入顺序,但只是作为实现细节,而不是像 3.7 中的特性。
【解决方案2】:

不要在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%')])]}

【讨论】:

  • 太棒了。只是有点晚了;)
猜你喜欢
  • 1970-01-01
  • 2013-12-05
  • 2016-04-22
  • 1970-01-01
  • 1970-01-01
  • 2020-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多