3

I have one dictionary of several pandas dataframes. It looks like this:

key  Value
A    pandas dataframe here
B    pandas dataframe here
C    pandas dataframe here

I need to extract dataframes from dict as a separate part and assign dict key as a name.

Desired output should be as many separate dataframes as many values of my dict have.

A = dict.values() - this is first dataframe

B = dict.values() - this is second dataframe

Note that dataframes names are dict keys.

I tried this code but without any success.

for key, value in my_dict_name.items():
    key = pd.DataFrame.from_dict(value)

Any help would be appreciated.

Okroshiashvili
  • 3,677
  • 2
  • 26
  • 40
  • I'm not really following, you say you have a dictionary of pandas dataframes. But it is unclear to me what te expected output should be. "Unpacking" a dictionary in variable names is really not a good idea at all (it is a severe anti-pattern). Since you basically never know what variables you will (re)define. – Willem Van Onsem Aug 04 '19 at 10:18
  • I have dictionary of dataframes. Values of dict are valid pandas dataframes and I need to unpack and assign dict keys as dataframe names. – Okroshiashvili Aug 04 '19 at 10:21
  • @NodarOkroshiashvilli: but now imagine that there is a key with the name `'list'`, `dict'`, etc. This will override the `list`, `dict`, ... builtin, and will therefore likely eventually crash the rest of your program. – Willem Van Onsem Aug 04 '19 at 10:22
  • @WillemVanOnsem I understand your point and also I see why it can be an anti-pattern. Thanks for suggestion – Okroshiashvili Aug 04 '19 at 10:36
  • 1
    Why unpack them? They are far more accessible if you just leave them alone inside that dict... – Dan Aug 04 '19 at 10:40

1 Answers1

3

It is not recommended, but possible:

Thanks @ Willem Van Onsem for better explanation:

It is a quite severe anti-pattern, especially since it can override existing variables, and one can never exclude that scenario

a = pd.DataFrame({'a':['a']})
b = pd.DataFrame({'b':['b']})
c = pd.DataFrame({'c':['c']})

d = {'A':a, 'B':b, 'C':c}
print (d)
{'A':    a
0  a, 'B':    b
0  b, 'C':    c
0  c}

for k, v in d.items():
    globals()[k] =  v

print (A)
   a
0  a

I think here the best is MultiIndex if same columns or index values in each DataFrame, also dictionary of DataFrame is perfectly OK.

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 2
    Perhaps it is better to stress the "not recommended" a bit. It is a quite severe anti-pattern, especially since it can override existing variables, and one can never exclude that scenario :) – Willem Van Onsem Aug 04 '19 at 10:23
  • I'm not as an experienced programmer as you are here guys but, I'll try my best. Until that @jezrael's solution works perfectly – Okroshiashvili Aug 04 '19 at 10:53