1

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

2 回答 2

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)

如果您不想为您的字典使用名称,请将它们放在一个列表中。

于 2012-04-15T05:03:17.670 回答
0

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

第一,如果你想创建一堆字典并打印出来,你会这样做:

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

会导致

['苹果','香蕉','榴莲']

这个 print(listDic['Fruit'][1]) 会导致

香蕉

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

于 2012-04-15T05:34:22.787 回答