I have a list like list = ['foo', 'bar', 'baz']
and am running a for-loop over the items. each time I do so, I'd like to create a dictionary named after the list element currently being looped over. For example
for element in list:
('%s' + '_' + 'dict') % element = {}
which, of course, doesn't work, giving me the error:
SyntaxError: can't assign to operator
Any ideas?
While it's possible to use eval
or to create new entries in the globals()
dictionary, it's almost certainly a bad idea. Instead, use your dictionary names as keys into another dictionary explicitly:
names = ['foo', 'bar', 'baz']
d = {}
for name in names:
d[name] = {}
You could also use a dict comprehension (or a generator expression in the dict
constructor, if you're in an earlier version of Python that doesn't allow dict comprehensions):
d = {name: {} for name in names}
# d = dict((name, {}) for name in names) # generator expression version for pre-2.7
You can do it with a dict. Like:
context = {} for element in list: context['%s_dict' % element] = {}
After that, you can use context['foo_dict'] to access the dictionaries you created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With