3

I have dictionaries named Bgf, Arf and so on which have multiple dataframes in them.

I am now creating a function that takes the name of the dictionary as a parameter by the user and then isolates dataframes whose names end with '_with_lof' in that dataframe. Now the dfs that are isolated must be stored in a new empty dict and the dict must have a name format as follows: 'dictionary'_filtered.

For example:

the dictionary Bgf has the following dfs:

s24_df
s25_df
s26_df
s27_df
dataframes
merged_df
s7_with_lof
s1_with_lof

Now, I want to isolate the dfs whose name contain the string _with_lof. Here s7_with_lof & s1_with_lof match. Now these two dfs must be stored a new dictionary whose name must be Bgf_filtered.

Similary, if the user gives Arf as the parameter, then the new dictionary name must be Arf_filtered.

My code:

def filtered(dictionary):
    filter_string = '_with_lof'
    **dictionary**_filtered = {k: v for (k, v) in Bgf.items() if filter_string in k}

Now, when the user does:

filtered('Bgf')

the Bgf must be used in the third line of the function for creating the new dict as Bgf_filtered.

Is there a way this can be done?

some_programmer
  • 3,268
  • 4
  • 24
  • 59
  • 4
    creating variable names dynamically is really bad idea. IMHO you should rethink your setup – buran Sep 10 '19 at 13:59
  • 3
    Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – glibdud Sep 10 '19 at 14:00
  • even though this is a bad idea, you can use `exec('varName = yourDataForTheVar')` – Oleg Vorobiov Sep 10 '19 at 14:17

1 Answers1

1

What you are doing smells of bad code, creating new variables like that isn't normal. And anyone who reads your code after you will curse you for it.

But still, you can do something like this:

def filtered(dictionary_name):
    filter_string = '_with_lof'
    globals()["%s_filtered" % (dictionary_name)] = {k: v for (k, v) in globals()[dictionary_name].items() if filter_string in k}

Normal code would be however, something that would return the filtered dictionary:

def filtered(dictionary):
    filter_string = '_with_lof'
    return {k: v for (k, v) in dictionary.items() if filter_string in k}

And then used like:

Bgf_filtered = filtered(Bgf)
Daid Braam
  • 173
  • 4