简体   繁体   中英

Create list of dictionaries from CSV in the same order using Python

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM