[lang-ref] ( parse_csv_to_dictionary ) ( python )
def test_parse_csv_to_dictionary():
# csv.DictReader
import csv
text = '''\
A,B,C,D
11,12,13,14
21,22,23,24
31,32,33,34
'''
expected = [
{'A': '11', 'B': '12', 'C': '13', 'D': '14'},
{'A': '21', 'B': '22', 'C': '23', 'D': '24'},
{'A': '31', 'B': '32', 'C': '33', 'D': '34'},
]
# with open('a.csv') as f:
with io.StringIO(text) as f:
reader = csv.DictReader(f)
rows = []
for row in reader:
rows.append(row)
assert rows == expected
# In this case, reading all rows at once is sufficient
# with open('a.csv') as f:
with io.StringIO(text) as f:
rows = list(csv.DictReader(f))
assert rows == expected