2

I'm trying to pull different data sets from SQL into python using different lists. For example I have the following data:

years = [2006, 2007, 2008]
2006 = [A, B, C, D, E]
2007 = [D, E, F, G, H, I, J, K]
2008 = [E, F, G]

Then to pull the data in, I'm using the following formulas:

df = pd.read_sql('SELECT %s from Table' % (str(x)), con=conn)

I'd like the string, str(x), to loop through each year first, then use the list for the corresponding year.

So, first it should do 2006 and loop through the 2006 list (A, B, C, D, E), run the rest of the program, then move on to 2007 and 2008.

I've used loops before but not sure how to loop between different lists.

2 Answers 2

3

If I understand correctly, you might want to express your data hierarchically:

years = {
    2006: ['A', 'B', 'C', 'D', 'E'],
    2007: ['D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'],
    2008: ['E', 'F', 'G'],
}

You could then loop over the years and then over the letters for each year like this:

for year, letters in years.items():
    # do something per year
    for letter in letters:
        # do something per letter for the year

Does this answer your question?

Sign up to request clarification or add additional context in comments.

Comments

1

Another advantage of cr3 solution is, you can address the items of each year easily, like:

print years[2006]

for y in years[2006]:
    print y

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.