Juan41
Juan41

Reputation: 25

Create a list name after another list items in a for loop

I'm new to python and programming. Im starting by seeing videos and reading books but I'm also doing a project and I'm stuck. So I have a list

list_ot = [123, 234, 774, 539, 492, 556]

And I have a csv file like this:

Sin, ot, cant
1, 123, 999
12, 234, 888
23, 123, 768
22, 774, 442

After opening the csv file, I want to make a for loop to create lists named after the items in the first list to save some rows in them according to an if statement. Something like this,

Reader = CSV.dictreader(file)

for i in list_ot:
    for row in reader:
        if I == row['ot']:
            (List_named_i).append(row)

Please help me :)

Upvotes: 0

Views: 2062

Answers (2)

Prasad
Prasad

Reputation: 6034

Another simpler alternative for this would be to make use of Pandas. Consider this code:

example.csv:

Sin,ot,cant
1, 123, 999
12, 234, 888
23, 123, 768
22, 774, 442

Code:

import pandas as pd
list_ot = [123, 774, 539, 492, 556]  # Removed 234 from your list for verification
df_csv = pd.read_csv('example.csv')
list_named_i = df_csv[df_csv.ot.isin(list_ot)]
print(list_named_i)

Output:

   Sin   ot  cant
0    1  123   999
2   23  123   768
3   22  774   442

Upvotes: 0

PM 2Ring
PM 2Ring

Reputation: 55479

As mentioned in the comments, it's not a good idea to dynamically create list names in a loop. Instead, you should use a collection like a list or dictionary to save your lists. I'll show how to do that below.

I also mentioned that doing this sort of thing won't work:

for i in list_ot:
    for row in reader:

On the first run of the outer for i in list_ot: loop we read through the whole file in the inner for row in reader: loop. And then when we get to the second run of the list_ot loop the file cursor will still be at the end of the file, so there will be no data left to read, and the inner loop will finish immediately. We could reset the file cursor to the start of the file, using the file's .seek method, but it's better to avoid re-reading the same file data multiple times.

Instead, when we read a row, we need to check if its 'ot' field matches one of the values in list_ot, and if it does we can save the row into the appropriate list.

The code below shows how to save your data into a dictionary of lists. Please study it carefully! This code was designed to run on Python 3, but it should also run correctly on Python 2 (although strictly speaking you should open the CSV file in binary mode in Python 2).

The csv.DictReader yields an OrderedDict of each row that it reads. This can be handy if you need to preserve the order of the fields in the row, but if you don't need to preserve the order then you can easily convert the OrderedDict to a plain dict, which is what m code does when it saves a row into the mylists dictionary.

import csv

list_ot = [123, 234, 774, 539, 492, 556]

# Create a dict of empty lists, with the numbers in list_ot as the keys
mylists = {k: [] for k in list_ot}

with open('data', 'r') as f:
    reader = csv.DictReader(f, skipinitialspace=True)
    for row in reader:
        print(row)
        ot = int(row['ot'])
        if ot in mylists:
            mylists[ot].append(dict(row))
print()

for k in list_ot:
    print(k, mylists[k])

output

OrderedDict([('Sin', '1'), ('ot', '123'), ('cant', '999')])
OrderedDict([('Sin', '12'), ('ot', '234'), ('cant', '888')])
OrderedDict([('Sin', '23'), ('ot', '123'), ('cant', '768')])
OrderedDict([('Sin', '22'), ('ot', '774'), ('cant', '442')])

123 [{'Sin': '1', 'ot': '123', 'cant': '999'}, {'Sin': '23', 'ot': '123', 'cant': '768'}]
234 [{'Sin': '12', 'ot': '234', 'cant': '888'}]
774 [{'Sin': '22', 'ot': '774', 'cant': '442'}]
539 []
492 []
556 []

Upvotes: 1

Related Questions