Home > Mobile >  Dynamically creating a dictionary from a single list of variables
Dynamically creating a dictionary from a single list of variables

Time:07-23

I would like to create a dictionary in which the key is the name of a pandas dataframe and the value is the dataframe itself:

import pandas as pd

df_x = pd.DataFrame({'a':[1, 2, 3]})
df_y = pd.DataFrame({'b':['a', 'b', 'c']})

dict_xy = dict({'df_x':df_x, 'df_y':df_y})

Is there a more efficient way to do this without having to write out each variable name twice (once as a string for the key and the other as a variable for the value)?

CodePudding user response:

How about:

dict_xy = {'df_x': pd.DataFrame({'a':[1, 2, 3]}), 'df_y': pd.DataFrame({'b':['a', 'b', 'c']})}

CodePudding user response:

Use dict comprehension

import pandas as pd

df_x = pd.DataFrame({'a':[1, 2, 3]})
df_y = pd.DataFrame({'b':['a', 'b', 'c']})
dfs = [dfx, df_y]
dict_names = ['df_x', 'df_y']

dicts = {k:v for k, v in zip(dict_names, dfs)}

This should allow you to have many more than 2 dictionaries in your dictionary of dictionaries.

CodePudding user response:

If your DataFrame variables are in the local namespace; iterate over locals() and create a dictionary of all the DataFrames.

>>> import pandas as pd
>>> a = 'foo'
>>> qrs = pd.DataFrame()
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
 '__loader__': <class '_frozen_importlib.BuiltinImporter'>,
 '__spec__': None, '__annotations__': {},
 '__builtins__': <module 'builtins' (built-in)>,
 'pd': <module 'pandas' from 'C:\\Python38\\lib\\site-packages\\pandas\\__init__.py'>,
 'a': 'foo',
 'qrs': Empty DataFrame
Columns: []
Index: []}
>>> isinstance(qrs,pd.DataFrame) 
True
>>> {k:v for k,v in locals().items() if isinstance(v,pd.DataFrame)}  
{'qrs': Empty DataFrame
Columns: []
Index: []}
>>>
  • Related