Driedan
Driedan

Reputation: 275

choose a list by string python

I'm having a problem with lists. Their are 4 list, each with a specific name:

a=[]
b=[]
c=[]
d=[]

Now I want to store values from a whole bunch of xls files in these lists. All these xls files have a name corresponding with the list. For example:

1-2013_a.xls
1-2014_b.xls

I iterate through these files with the following code:

rootdir='C:\users\desktop\folder'  
for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        ....

Here i want to append date from the xls file to the list with the same letter as in the name of the file. I could do it like this:

rootdir='C:\users\desktop\folder'  
for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        if(file[7]=='a'):
           ....
        if(file[7]=='b'):
           ....
        if(file[7]=='c'):
           ....
        if(file[7]=='d'):
           ....

But in my program i have 20 lists, so 20 times an if-condition is a bit odd. Is it possible to call a list by a string without using a dictionary ?

Thanks for helping me in advance

Upvotes: 1

Views: 57

Answers (1)

Anshul Goyal
Anshul Goyal

Reputation: 76897

You can use a dictionary of lists:

dct = {"a": [],
    ...
    "d": []}

And then, you can do if file[7] in dct: and access the list using dct[file[7]]


Even better, you can use a defaultdict

from collections import defaultdict
dct = defaultdict(list)

Now, within your code, you simply write:

rootdir='C:\users\desktop\folder'  
for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        ...
        dct[file[7]].append(values)

This way, you won't have to define any keys of the dictionary, they will be initialized on the go with an empty list.

Upvotes: 4

Related Questions