Python:使用字符串作为变量?

时间:2012-04-15 04:56:45

标签: python string variables

我想编写一个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'}}

2 个答案:

答案 0 :(得分: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)

如果您没有使用词典的名称,请将它们放在列表中。

答案 1 :(得分:0)

您似乎正在尝试创建混合数据类型,但我不清楚您想要什么样的结构,所以我会给你2个答案,希望一个是正确的。

第1,如果您正在尝试创建一堆字典并打印它,您可以这样做:

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

第二,按照你给出的例子,可能是为了创建一个列表字典。例如

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

你可以像这样访问它:

print(listDic['Fruit'])

会导致

  

['苹果','Bannanas','榴莲']

这个     打印(listDic [ '果实'] [1]) 会导致

  

Bannanas

如果我错过了您想要的答案,或者您想要更多细节,请发表评论。