-3

I have a dictionary that stores all the dataframes from a given excel file.

import pandas as pd
xl=pd.ExcelFile('pandas_worksheets.xlsx')

mydic={}
for i in xl.sheet_names:
    mydic[i] = xl.parse(i)

I can call any dataframe sheet using this syntax:

mydic['olympic']

But how do I simply call "olympic" to return that dataframe? (without using mydic)

somthing like this works...

olympic = xl.parse('olympic')

But the same logic does not work in the for loop

for i in xl.sheet_names:
    i = xl.parse(i)

It saves the last dataframe as literal i instead of replacing it with sheet-name.


update:

mydic={'a':1, 'b': 2}

for i in mydic:
    i = mydic[i]

a

NameError: name 'a' is not defined

(expected value 1 instead of NameError)

shantanuo
  • 31,689
  • 78
  • 245
  • 403
  • Can you explain this a bit more? It looks like you want to dynamically generate variables, why do you need to do this? – AMC Jan 13 '20 at 02:35

1 Answers1

3

Although it's frowned upon injecting and polluting the global name space when you can maintain a dictionary, you can still do it in a few ways:

With globals()

mydic={'a':1, 'b': 2}

globals().update(mydic)
print a
print b

Output:

1
2

With exec():

mydic={'a':1, 'b': 2}

for i in mydic:
    exec("%s = mydic['%s']"%(i,i))

print a
print b

Output:

1
2
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78