0

I want to create a few dictionaries: Dict1, Dict2, Dict3, ..., Dict15 within a for-loop.

dictstr = 'dict'
for ii in range(1,16):
    dictstrtemp = dictstr
    b = str(ii)
    dictstrtemp += b #--> "dictii" created; where ii is 1, 2, ..., 15
    print(dictstrtemp)

The output are 15 strings, from "dict1" to "dict15". Now I want to assign each "dictii" some entries and reference them each outside of the for-loop. How do I do that? If I add "dictstrtemp = {}", then I can't reference it as "dict4" (for exapmle), it is only dictstrtemp. But I want to be able to enter "dict4" in the console and get the entries of dict4.

Idontcare
  • 11
  • 5

2 Answers2

2
dictstr = 'dict'
dictlist = []
for ii in range(16):
    dictstrtemp = dictstr
    b = str(ii)
    dictstrtemp += b #--> "dictii" created; where ii is 1, 2, ..., 15
    dictlist.append(dictstrtemp)
    print(dictstrtemp)

print(dictlist[4])
'dict4'

Or with list comprehension:

dictstr = 'dict'
dictlist = [dictstr + str(i) for i in range(16)]
Anton Protopopov
  • 30,354
  • 12
  • 88
  • 93
0

Try this. Here I stored the dictionaries in another dict, using the indes as a number... you can use something else.

dict_of_dicts = {}

for ii in range(16):
    my_dict = {'dict' + str(ii) : 'whatever'}
    dict_of_dicts[ii] = my_dict

# now here, access your dicts
print dict_of_dicts[4]

# will print {'dict4' : whatever}
vlad-ardelean
  • 7,480
  • 15
  • 80
  • 124