gpt4 book ai didi

python - 将 csv.DictReader 对象转换为字典列表?

转载 作者:IT老高 更新时间:2023-10-28 21:17:49 26 4
gpt4 key购买 nike

一个csv文件names.csv有内容:

first_name last_name
Baked Beans
Lovely Spam
Wonderful Spam

我想将它读入字典列表,第一行包含键:

>>> import csv
>>> with open('names.csv') as csvfile:
... reader = csv.DictReader(csvfile)
... for row in reader:
... print(row['first_name'], row['last_name'])
...
Baked Beans
Lovely Spam
Wonderful Spam

但是readercsv.DictReader的类型吗?如何将 reader 转换为字典列表?谢谢。

最佳答案

import csv
with open("in.csv") as csvfile:
reader = csv.DictReader(csvfile,delimiter=" ")
print(list(reader))
[{'first_name': 'Baked', 'last_name': 'Beans'}, {'first_name': 'Lovely', 'last_name': 'Spam'}, {'first_name': 'Wonderful', 'last_name': 'Spam'}]

如果分隔符实际上不是 则需要指定 "" 或其他任何内容。

为了消除混淆,代码在 python3.6 上也可以正常工作,唯一的区别是使用 DictReaderOrderdicts默认情况下:

In [1]: import csv
...: with open("in.csv") as csvfile:
...: reader = csv.DictReader(csvfile, delimiter=" ")
...: print(list(reader))
...:
[OrderedDict([('first_name', 'Baked'), ('last_name', 'Beans')]), OrderedDict([('first_name', 'Lovely'), ('last_name', 'Spam')]), OrderedDict([('first_name', 'Wonderful'), ('last_name', 'Spam')])]

您可以完全一样地访问 key ,OrderedDict 只是保持 key 插入顺序:

In [2]: import csv
...: with open("in.csv") as csvfile:
...: reader = csv.DictReader(csvfile, delimiter=" ")
...: for dct in reader:
...: print(f"{dct['first_name']} {dct['last_name']}")
...:
...:
Baked Beans
Lovely Spam
Wonderful Spam

py3.6 实际上也是如此,所以如果出于某种原因你真的想要一个 dict:

In [5]: import csv
...: with open("in.csv") as csvfile:
...: reader = csv.DictReader(csvfile, delimiter=" ")
...: for dct in map(dict, reader):
...: print(dct)
...: print(f"{dct['first_name']} {dct['last_name']}")
...:
...:
{'first_name': 'Baked', 'last_name': 'Beans'}
Baked Beans
{'first_name': 'Lovely', 'last_name': 'Spam'}
Lovely Spam
{'first_name': 'Wonderful', 'last_name': 'Spam'}
Wonderful Spam

py3.6 中插入时的排序保留是一个实现细节,可能会发生变化,但如果我们有足够多的人使用它,它可能只需要保留 :)

关于python - 将 csv.DictReader 对象转换为字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29432912/

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