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 :)