2

I would like to define a dictionary with a name that changes dynamically. For example:

Dictname = 'Forrest'
Forrest = {}

The parameter Dictname is received from a textfile, the value forrest will be different every time the script runs

milanbalazs
  • 4,811
  • 4
  • 23
  • 45
Woolfy
  • 35
  • 2
  • 1
    You can do: `globals()[Dictname] = {}` – Tom Karzes Aug 05 '19 at 04:34
  • 1
    you can keep it in other dictionary - `data = dict()`, `data[Dictname] = {}` And then you can easily get something from dictionary - `print(data[Dictname])`. Or simply forget name `Forrest` and always use the same name. – furas Aug 05 '19 at 04:51
  • 4
    see [this](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables). It's just not a good idea. It's awkward to do for a reason. When people want to do this, it's generally because of an [XY problem](https://en.wikipedia.org/wiki/XY_problem). – Paul Rooney Aug 05 '19 at 05:02

1 Answers1

-1

Not sure if I read the requirement correctly but here is something to try. I edited the answer after seeing the globals() comment.

Answer 1 is my original answer. However the next answer, answer 2, is more straightforward but is not significantly different from what has already been suggested in comments.

Answer 1.

Dictionary = 'forrest'
exec('%s={}'%Dictionary)
exec('%s[\'mykey\']=123456'%Dictionary)
print(forrest)

Answer 2.

Dictionary = 'forrest'
globals()[Dictionary]={}
globals()[Dictionary]['Mykey']=123456
print(globals()[Dictionary])
Amit
  • 2,018
  • 1
  • 8
  • 12