Python 将 csv.DictReader 对象转换为字典列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29432912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a csv.DictReader object to a list of dictionaries?
提问by Tim
A csv file names.csv
has content:
一个 csv 文件names.csv
包含以下内容:
first_name last_name
Baked Beans
Lovely Spam
Wonderful Spam
I would like to read it into a list of dictionaries, with the first row containing the keys:
我想将它读入字典列表,第一行包含键:
>>> 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
But is the type of reader
csv.DictReader
?
How can I convert reader
into a list of dictionaries?
Thanks.
但类型是reader
csv.DictReader
? 如何转换reader
为字典列表?谢谢。
回答by alecxe
Use list()
:
使用list()
:
print(list(reader))
Demo:
演示:
>>> with open('names.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'}]
回答by Padraic Cunningham
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'}]
If the delimiter is not actually a ,
you need to specify " "
or whatever it is.
如果分隔符实际上不是 a,
您需要指定" "
或无论如何。
Just to clear any confusion, the code works fine for python3.6 also, the only difference is that using DictReadergives Orderdictsby default:
为了消除任何混淆,该代码也适用于 python3.6,唯一的区别是使用DictReader默认提供Orderdicts:
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')])]
You can access keys exactly the same, an OrderedDict
just keeps key insertion order:
您可以完全相同地访问密钥,OrderedDict
只是保持密钥插入顺序:
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
Which py3.6 actually does too, so if for some reason you really want a dict:
哪个 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
The ordering retention on insertion in py3.6 is an implementation detailand may change, but if enough of us use it, it may just have to stay :)
py3.6 中插入时的排序保留是一个实现细节,可能会改变,但如果我们有足够多的人使用它,它可能只需要保留 :)
回答by Exebit
Create function
创建函数
import csv
def csv_to_dict(filename):
result_list=[]
with open(filename) as file_obj:
reader = csv.DictReader(file_obj, delimiter=delimiter)
for row in reader:
result_list.append(dict(row))
return result_list
and use it:
并使用它:
list_of_dicts = csv_to_dict('names.csv')
回答by Ninga
The csv.DictReader creates a dictreader object as noted in the title. This object is only useable while the file is open and cant be sliced.
csv.DictReader 创建一个 dictreader 对象,如标题中所述。此对象仅在文件打开且无法切片时可用。
To convert the object to a list as per the title....
要根据标题将对象转换为列表....
list_of_dicts = list(your_dictreader_object)