1

I have a dictionary that has dataframes in values, something like this -

dict = {'demand': demand_df, 'supply':supply_df, 'prod': prod_df}

then, I have a list like this -

list = ['demand', 'supply', 'prod']

I want to create individual dataframes objects using a loop, resulting in below -

demand = demand_df
supply = supply_df
prod =  prod_df

My try -

for i in list:
   i = dict[i]

This obviously is giving an error. How do I correct it?

jpp
  • 159,742
  • 34
  • 281
  • 339
Karvy1
  • 959
  • 6
  • 14
  • 25
  • You already have a dictionary. Why do you need to name each string accordingly ? Just access your dataframes using `dict['demand']` or `dict['supply']`. (Also, do not name your variable `dict` because it overrides python builtin `dict`) – rafaelc Aug 04 '18 at 13:18
  • Are demand_df, supply_df etc. strings? or variables – Gareth Ma Aug 04 '18 at 13:19
  • @RafaelC I am using these dataframes in pandasql's sqldf function. It gives an error if I use dict['demand']. – Karvy1 Aug 04 '18 at 13:23
  • Have a look here: https://stackoverflow.com/questions/18837262/convert-python-dict-into-a-dataframe – Sheldore Aug 04 '18 at 13:25
  • @Karvy1 Sorry but I didn't read that you're using Pandas. Can you verify if my answer works under your 'panda dataframes'? – Gareth Ma Aug 04 '18 at 13:27
  • Commented to your answer, mate! – Karvy1 Aug 04 '18 at 13:34

1 Answers1

0

First, do not name variables after built-ins, e.g. use d instead of dict and lst instead of list.

Second, do not dynamically name variables. It is poor practice, makes your code intractable, clutters the namespace, removes the connection between related variables.

Just access a dictionary value directly:

d = {'demand': demand_df, 'supply':supply_df, 'prod': prod_df}

d['demand']  # retrieve demand_df

There is, in my experience, no reason to dynamically name a dictionary value.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • Thanks for your inputs. I needed that for using dictionary values in pandasql. I have created a seperate question to address that. https://stackoverflow.com/questions/51686216/using-dictionary-values-in-pandasql – Karvy1 Aug 05 '18 at 07:50
  • 1
    Excellent. Context is key here, and you've given it in your new question. thanks. – jpp Aug 05 '18 at 09:42