在 for 循环中动态创建多个字典并在循环外引用它们

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

我想在 for 循环中创建一些词典:Dict1、Dict2、Dict3、...、Dict15。

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)

输出15个字符串,从"dict1"到"dict15"。 现在我想为每个 "dictii" 分配一些条目并在 for 循环之外引用它们。我怎么做?如果我添加 "dictstrtemp = {}",那么我不能将其引用为 "dict4"(例如),它只是 dictstrtemp。但是我希望能够在控制台中输入 "dict4" 并获取 dict4.

的条目
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'

list comprehension:

dictstr = 'dict'
dictlist = [dictstr + str(i) for i in range(16)]

试试这个。在这里,我将字典存储在另一个字典中,使用索引作为数字......你可以使用其他东西。

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}