How can I store lines from a CSV file in a dictionary?

Viewed 148

I must extract with Python all the lines at index 1 and 5 of from a CSV file and store them in the dictionary "names". But, since I am new in Python, I am really struggling with thisk task. This is my code:

names = {}
with open("../data/names.csv") as file:
    for line in file:
        print(line)

output:

Id,Name,Year,Gender,State,Count
1,Mary,1910,F,AK,14
2,Annie,1910,F,AK,12
3,Anna,1910,F,AK,10
4,Margaret,1910,F,AK,8
5,Helen,1910,F,AK,7
6,Elsie,1910,F,AK,6
...

If I try to store the index 1 (the string "Name") and the index 5 (int) of the lines in the dictionary "names", I obtain a wrong output. Here the code:

names = {}
with open("../data/names.csv") as file:
    for line in file:
        names = {"name": line[1], "count": line[5]}
print(names)

The (wrong) output:

{'name': '6', 'count': '2'}
1 Answers

The desired output data structure is not specified, and I think the question is about columns (not rows)

with open('sample.csv','r') as file_handle:
    file_content = file_handle.read()

list_of_dicts = []
for index, line in enumerate(file_content.split('\n')):
    line_as_list = line.split(',')
    if index==0:
        pass # ignore the headers
    else:
        line_dict = {'name': line_as_list[1], 'count': line_as_list[5]}
        list_of_dicts.append(line_dict)
print(list_of_dicts)

If the desired data structure is a single dict with a list of entries from each line,

results = {'name': [], 'count': []}
for index, line in enumerate(file_content.split('\n')):
    line_as_list = line.split(',')
    if index==0:
        pass # ignore the headers
    else:
        results['name'].append(line_as_list[1])
        results['count'].append(line_as_list[5])
print(results)
Related