Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在for循环中动态创建几个字典,并在循环外引用它们_Python_Python 3.x_For Loop_Dictionary_On The Fly - Fatal编程技术网

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

Python 在for循环中动态创建几个字典,并在循环外引用它们,python,python-3.x,for-loop,dictionary,on-the-fly,Python,Python 3.x,For Loop,Dictionary,On The Fly,我想在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”。

我想在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”。 现在我想给每个“dicti”分配一些条目,并在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'
或通过
列表理解

dictstr = 'dict'
dictlist = [dictstr + str(i) for i in range(16)]
或通过
列表理解

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

试试这个。在这里,我将字典存储在另一个dict中,使用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}

试试这个。在这里,我将字典存储在另一个dict中,使用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}

不可能的。你可以创建
dict
list
,然后通过索引访问它,比如
dict\u list[4]
@antonprotopov我不会说“不可能”,但肯定是不可取的;不过,这张单子是正确的答案。这张单子很好用。谢谢你的及时答复。不可能。你可以创建
dict
list
,然后通过索引访问它,比如
dict\u list[4]
@antonprotopov我不会说“不可能”,但肯定是不可取的;不过,这张单子是正确的答案。这张单子很好用。谢谢你的及时答复。