【问题标题】:Create list of dictionaries from CSV in the same order using Python使用 Python 以相同的顺序从 CSV 创建字典列表
【发布时间】:2017-12-08 05:14:39
【问题描述】:

考虑一个 CSV,

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

如何像这样以相同的顺序创建字典列表

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

我尝试了以下代码,但顺序不同

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

以上代码的输出,

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

有什么办法可以按相同顺序获取吗?

谢谢!

【问题讨论】:

标签: python list csv dictionary


【解决方案1】:

由于字典本质上是无序的,因此您需要在列表中的每个字典上加上 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')])]

并且工作正常:

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

注意:不能将输出中的OrderedDict()换成普通字典,否则会再次无序。如果我们想要在 python 中订购字典,这是我们必须付出的代价之一。

【讨论】:

  • 我刚开始接触 Python。暂时看来还可以。但我一定会深入研究这一点
  • @3P3 这确实是唯一简单的方法。您真的必须订购col1col2col3 吗?
  • 是的,因为数据需要传递并创建一个XPT文件。那就是期望顺序相同。这对 QA 来说也很重要
猜你喜欢
  • 2018-07-29
  • 2021-07-03
  • 1970-01-01
  • 2014-11-11
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
  • 2016-11-20
  • 2020-10-30
相关资源
最近更新 更多