我想寫一個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'}}
使用列表(不包括索引器中的「D」)或其他字典。你稍後會感謝你。 – 2012-04-15 04:58:35
或者使用字典字典 - 計算密鑰仍然比計算機名稱更好 - 如果你想能夠任意命名它們而不僅僅是連續的數字。 – agf 2012-04-15 05:00:42
你的'數字'循環應該是:'範圍內的數字(1,11):' – 2012-04-15 05:07:59