pythonpython-3.xfor-loopdictionaryon-the-fly

Create several dictionaries on the fly in a for-loop and reference them outside of the loop


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.


Solution

  • 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)]