简体   繁体   English

使用Python以相同的顺序从CSV创建字典列表

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

Consider a CSV, 考虑一个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: 由于字典本质上是无序的,因此您需要在列表中的每个字典上包装一个OrderedDict ,这些字典需要事先排序:

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. 注意:您不能用普通字典替换输出中的OrderedDict()包装,否则它将再次无序。 This is one of the prices we have to pay if we want ordered dictionaries in python. 如果要使用python订购字典,这是我们必须支付的价格之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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