Search code examples
pythondictionaryfor-loopenumeration

Creating a Dict for the name and a list of the values from a CSV file


I'm a beginner at python and was trying to figure out a way to create a dict of names and a list of the values from a csv file. I came across this code online. It works, but i cant understand any of it.

Any help would be much appreciated.

my main areas where I'm feeling lost are the for loop, then strand = .... and finally curr_row = row.strip().split(',')]

Code:

strands = []
persons = {}

for ind, row in enumerate(csv_file):
   if ind == 0:
       strand = [strand for strand in row.strip().split(',')][1:]
   else:
       curr_row = row.strip().split(',')
       persons[curr_row[0]] = [int(x) for x in curr_row[1:]]```

the csv file looks like this:
name,AGATC,AATG,TATC
Alice,2,8,3
Bob,4,1,5
Charlie,3,2,5


output : {'Alice': [2, 8, 3], 'Bob': [4, 1, 5], 'Charlie': [3, 2, 5]}



Solution

  • The for loop with enumerate will get ind as the index of the line and the variable row is the data on that line.

    The strand is the first line on the csv_file and a list comprehension is being run on that line. If you aren't sure what a list comprehension is, here is a link explaining: https://www.pythonforbeginners.com/basics/list-comprehensions-in-python

    The row.strip() function will remove all whitespace.

    The .split(',') function will turn that line in the csv_file into a list of items separated by the ',' comma.

    So strand would be ['name', 'AGATC', 'AATG', 'TATC'].

    The curr_row is doing the same thing with the following lines.

    So line 2 in the csv_file is:

    Alice,2,8,3

    After running,

    curr_row = row.strip().split(',')
    

    on the second line, curr_row will equal ['Alice', 2, 8, 3]

    persons[curr_row[0]] = [int(x) for x in curr_row[1:]]
    

    The line above the adds it to the dictionary with key 'Alice' and then loops over the rest of the numbers with a list comprehension which is why it starts at 1 if you look at the list indexing.

    curr_row[1:]
    

    If the link did not help then this video by Corey Schafer might, it's how I learned how to use list comprehensions.

    https://www.youtube.com/watch?v=3dt4OGnU5sM&t=3s

    I hope that helped.