Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

naming dictionaries after list items

Tags:

python

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?

like image 229
user139014 Avatar asked Dec 15 '22 08:12

user139014


2 Answers

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
like image 65
Blckknght Avatar answered Jan 03 '23 14:01

Blckknght


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.

like image 41
nicky_zs Avatar answered Jan 03 '23 13:01

nicky_zs