Search code examples
pythondictionarycollectionsordereddict

How to print the output in order in python dictionary


I tried to print the output in order as mentioned in header but still im receiving the output in unordered. Please help on this.

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%

Code

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)

Output

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

Expected Result

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

Solution

  • Just do not create a dict, simply pass zip result to collections.OrderedDict:

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

    This is not required for Python 3.7 and higher, as since 3.7 dict keeps the order of the inserted elements (https://docs.python.org/3/whatsnew/3.7.html)