簡體   English   中英

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

嘗試這個。 在這里,我將字典存儲在另一個字典中,使用indes作為數字...您可以使用其他字典。

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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM