1 回答

TA貢獻1880條經(jīng)驗 獲得超4個贊
不要在循環(huán)外創(chuàng)建變量,而是在其中創(chuàng)建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']})
添加回答
舉報