我试着在下面的方法中列出一个dicts列表,希望我可以按索引号开始创建我的dicts列表。但错误当然是"名称dogdict没有定义。"
我如何声明dogdict
以使其顺利运行?
import random
slist=['big','medium','small']
for i in range(10):
dogdict[i]['name']=random.randint(1,100)
dogdict[i]['size']=random.choice(slist)
print("it's dog time... a list of dict")
for i in range(10):
print(i)
print(dogdict[i])
答案 0 :(得分:3)
您无法将商品放入不存在的容器中。您首先必须初始化,然后您可以追加在容器的尾部添加新项目:
import random
slist = ['big','medium','small']
dogdict = [] # initialize list
for _ in range(10): # index is never used
d = {} # initialize dict
d['name'] = random.randint(1,100)
d['size'] = random.choice(slist)
dogdict.append(d)
当然,有更优雅的方式来做到这一点。您可以使用 list comprehension 来构建将放置在结果列表中的词典:
doglist = [{'name': random.randint(1,100), 'size': random.choice(slist)}
for _ in range(10)]