1

Consider a CSV,

col1, col2, col3
1000, Star, True
2000, Moon, False

How to create a list of dictionaries in the same order like this

[{'col1': '1000', 'col2': 'Star', 'col3': 'TRUE'}, {'col1': '2000', 'col2': 'Moon', 'col3': 'FALSE'}]

I have tried with following code but not getting in the same order

with open('sample.csv') as f:
    rows = [{k: v for k, v in row.items()}
        for row in csv.DictReader(f, skipinitialspace=True)]

Output of above code,

[{'col2': 'Star', 'col3': 'TRUE', 'col1': '1000'}, {'col2': 'Moon', 'col3': 'FALSE', 'col1': '2000'}]

Is there any solution to get in the same order?

Thanks!

  • Seems duplicated: https://stackoverflow.com/questions/1885324/is-it-possible-to-keep-the-column-order-using-the-python-csv-dictreader – Yu-Lin Chen Dec 08 '17 at 05:23

1 Answers1

0

Since dictionaries are inherently unordered, you need wrap an OrderedDict on each of the dictionaries in your list, which need to be sorted beforehand:

import csv
from collections import OrderedDict

with open('sample.csv') as f:
    rows = [OrderedDict(sorted(dict((k, v) for k, v in row.items()).items())) for row in csv.DictReader(f, skipinitialspace=True)]

>>> print(rows)
[OrderedDict([('col1', '1000'), ('col2', 'Star'), ('col3', 'True')]), OrderedDict([('col1', '2000'), ('col2', 'Moon'), ('col3', 'False')])]

And works normally:

>>> print(rows[0]['col1'])
1000
>>> print(rows[1]['col1'])
2000
print([key for key in rows[0]])
['col1', 'col2', 'col3']

Note: You can't replace the OrderedDict() wrapping in the output with a normal dictionary, otherwise it will be unordered again. This is one of the prices we have to pay if we want ordered dictionaries in python.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75
  • I just started with Python. Seems okay for the time being. But I will surely look deep on this –  Dec 08 '17 at 05:50
  • @3P3 This is really the only easy way to do this. Do you really have to have `col1`, `col2` and `col3` ordered? – RoadRunner Dec 08 '17 at 05:53
  • Yes, since the data need to pass and create a XPT file. thats expecting the order same. Also this matter for QA as well –  Dec 08 '17 at 06:18