2012-04-15 41 views
1

我想寫一個python腳本,一次創建幾個字典然後打印字典,但我不知道如何將字符串轉換爲變量。Python:使用一個字符串作爲變量?

number = 0 

while (number < 10): 
    number = number + 1 
    dictionarynumber = ("D"+str(number)) # creates the dictionarys name(D1,D2,D3,D4,D5,D6,D7,D8,D9,D10) 
    var(dictionarynumber) = {"Fruit":"Apple","Book":"Oliver Twist","Building":"White House"} #Of course var() doesn't work but I placed it here to get my point across 
    print(dictionarynumber) 

後回答:

我喜歡關於字典的想法,並採取了不必要的 「d」 是有道理的。你們對此有何看法?

dict = {} 
n = 0 

while (n < 10): 
    n = n + 1 
    d = n 
    d = {"Key":"Information"} 
    dict[n] = d 

print(dict) 


# Output = 
#   {1: {'Key': 'Information'}, 
#   2: {'Key': 'Information'}, 
#   3: {'Key': 'Information'}, 
#   4: {'Key': 'Information'}, 
#   5: {'Key': 'Information'}, 
#   6: {'Key': 'Information'}, 
#   7: {'Key': 'Information'}, 
#   8: {'Key': 'Information'}, 
#   9: {'Key': 'Information'}, 
#   10: {'Key': 'Information'}} 
+5

使用列表(不包括索引器中的「D」)或其他字典。你稍後會感謝你。 – 2012-04-15 04:58:35

+0

或者使用字典字典 - 計算密鑰仍然比計算機名稱更好 - 如果你想能夠任意命名它們而不僅僅是連續的數字。 – agf 2012-04-15 05:00:42

+1

你的'數字'循環應該是:'範圍內的數字(1,11):' – 2012-04-15 05:07:59

回答

4

如果你想給每個字典一個名字,把它們放在一個字典中。

dicts = {} 
# dict_list = [] 
for i in xrange(10): 
    dictionary_key = ('d{0}'.format(i)) 
    dict_item = {"Fruit":"Apple","Book":"Oliver Twist","Building":"White House"} 
    dicts[dictionary_key] = dict_item 
    # dict_list.append(dict_item) 

如果您沒有爲字典使用名稱,請將它們放入列表中。

+0

空白字典,我不知道你可以做到這一點。似乎是個好主意。 – RandomPhobia 2012-04-15 06:01:54

+0

+1開啓和關閉句子 – 2014-11-02 08:41:34

0

你似乎試圖創建一個混合的數據類型,但我不清楚你想要什麼樣的結構,所以我會給你2個答案,並希望一個是正確的。

月1日,如果你想創建一批字典和打印它,你會做這樣的:

diclist = [{"Fruit":"Apple"},{"Book":"Oliver Twist"},{"Building":"White House"}] 
print(diclist[1]) 

2日,由你給你的目標可能是創建一個字典的例子中去列表。例如

listDic = {'Fruit':['Apples', 'Bannanas', 'Durian'], 'Book':['Oliver Twist','Flashman', 'Catch 22']} 
print (listDic) 

,您可以訪問它像這樣:

print(listDic['Fruit']) 

會導致

[ '蘋果', 'Bannanas', '飄飄']

and this print(listDic ['Fruit'] [1]) res res ULT在

Bannanas

如果我錯過了答案你想要的或想詳細剛落評論。