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.
DictReader returns a file-like object. It still reads the data from the csv file in one row at a time, but the returned rows are ordered dictionaries instead of lists. In this case, data will be a list of OrderedDict objects with the mapping from the headers to each item in the row.
The best way to convert a CSV file to a Python dictionary is to create a CSV file object f using open("my_file. csv") and pass it in the csv. DictReader(f) method. The return value is an iterable of dictionaries, one per row in the CSV file, that maps the column header from the first row to the specific row value.
The DictReader () is used to read the file of the csv in the format of the dict object.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With