1 回答

TA贡献1880条经验 获得超4个赞
不要在循环外创建变量,而是在其中创建item:
list = {"shopping_list": []}
count = 0
stuff = [{"name": "Gold Badge"}, {"name": "Silver Badge"}, {"name": "Bronze Badge"}]
for s in stuff:
item = {}
item["level"] = count
item["position"] = count * 10
item["item_name"] = s["name"]
list["shopping_list"].append(item)
count += 1
print(list)
输出:
{'shopping_list': [{'level': 0, 'position': 0, 'item_name': 'Gold Badge'}, {'level': 1, 'position': 10, 'item_name': 'Silver Badge'},{'level': 2, 'position': 20, 'item_name': 'Bronze Badge'}]}
正如@DeepSpace 指出的那样,您还可以使用字典文字:
for s in stuff:
list["shopping_list"].append({'level': count, 'position': count * 10, 'item_name': s['name']})
count += 1
事实上,你可以去掉 count 变量,也可以这样做:
for count, s in enumerate(stuff):
list["shopping_list"].append({'level': count, 'position': count * 10, 'item_name': s['name']})
添加回答
举报