How can I give a dictionary a name from a variable value?
An example of what I'm trying to build:
apache['name'] = "Apache Web Server"
apache['category'] = "web"
apache['version'] = "2.2.14-4"
However I don't know the dictionary's name in advance, that arrives as variable, e.g. dname = 'apache'
. Dname is parsed from a text file. The logic is: "First word after delimiter is dict_name; next n lines are split into key:value pairs for dict_name; skip to next delimiter; repeat until end".
What doesn't work:
key = 'category'
value = 'web'
dname[key] = value
TypeError: 'str' object does not support item assignment
eval(dname)[key] = value
NameError: name 'apache' is not defined
getattr(dname, '__contains__')[key] = value
and similar attempts with keywords from dir(dname)
spawn only errors. (Because getattr is only for functions and modules?)
From How to create a dictionary based on variable value in Python I'm introduced to vars()
, but it wants the dictionary to exist already?
vars(dname)[key] = value
TypeError: vars() argument must have __dict__ attribute
This question's title is the closest sounding I've found to what I'm after, but the answers are about using variables for keys, not the dict name: Create a dictionary with name of variable