0

I have a set of string variables in Python code. I want to create a set of dictionaries with names as strings. And I also want to assign values for these dictionary using variable values.

I am wondering how to write code for this?

Please note that, in below code, at line my_func1_dict = xxx, I also need to fill the func1 with a variable value.

For example:

name = {func1, func2, fun3}
exec("my_%s_dict = %s" % (name[0], {}))
my_func1_dict = xxx
Henry Woody
  • 14,024
  • 7
  • 39
  • 56
aaltonen
  • 31
  • 5
  • 1
    Common rookie question. Use a dict of dicts. – Mad Physicist Dec 28 '18 at 03:55
  • I'm not sure exactly what you're trying to do. It seems that if you want variable names for your dictionaries, you should put them inside a containing dictionary rather than do this. Consider that you'll have to continue to use `exec` to access these dictionaries programmatically in the future. – Henry Woody Dec 28 '18 at 03:55
  • @MadPhysicist The duplicate link you have given does not address the question of aaltonen, please provide a better link – ycx Dec 28 '18 at 04:05

1 Answers1

0
name = ['func1', 'func2', 'func3']
exec("my_%s_dict = %s" % (name[0], {}))
my_func1_dict['somekey'] = 'xxx'
print(my_func1_dict)
#{'somekey': 'xxx'}

Fixed your code for you
You can also use a dict of dicts like what Mad_Physicist suggested, but that would require more code

ycx
  • 3,155
  • 3
  • 14
  • 26