Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

python - Convert a csv.DictReader object to a list of dictionaries?

A csv file names.csv has content:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.

Just to clear any confusion, the code works fine for python3.6 also, the only difference is that using DictReader gives Orderdicts by default:

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:

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:

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 detail and may change, but if enough of us use it, it may just have to stay :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...