gpt4 book ai didi

python - 让字典从 csv 文件中读取有序字典

转载 作者:行者123 更新时间:2023-11-30 23:13:15 25 4
gpt4 key购买 nike

何时 using csv.DictReader to read a csv file into a list of dictionaries ,如何使每个字典成为按 csv 文件中相同顺序排序的有序字典?谢谢。

import csv
import collections
with open("in.csv") as csvfile:
reader = csv.DictReader(csvfile,delimiter=" ")
lst = list(reader)
lst_orderedDict = [collections.OrderedDict(x) for x in lst]

lst_orderedDict 中的每个有序字典在 csv 文件中的排序方式不同?

最佳答案

将 OrderedDict 与 csv.reader 一起使用:

from collections import OrderedDict
with open("in.csv") as csvfile:
reader = csv.reader(csvfile,delimiter=" ")
keys = next(reader)
print([OrderedDict(zip(keys,row)) for row in reader ])


[OrderedDict([('first_name', 'Baked'), ('last_name', 'Beans')]), OrderedDict([('first_name', 'Lovely'), ('last_name', 'Spam')]), OrderedDict([('first_name', 'Wonderful'), ('last_name', 'Spam')])]

或者将两者结合起来:

from collections import OrderedDict

with open("in.csv") as csvfile:
reader = csv.DictReader(csvfile,delimiter=" ")
keys = reader.fieldnames
r = csv.reader(csvfile,delimiter=" ")
print([OrderedDict(zip(keys, row)) for row in r])

关于python - 让字典从 csv 文件中读取有序字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29434296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com