我正在尝试使用for循环将不同的字典添加到同一列表中,但是我不知道如何在每次迭代中生成新的字典。我使用的文件具有以下格式:
食谱名称
食谱
食谱名称
食谱
,其中食谱是“ 1杯面粉”。有十行食谱
我正在尝试将每个食谱添加到不同的词典,并将这些词典附加到列表中。这是我所拥有的:
fhand = open("recipe.txt").read()
lines = fhand.split('\n')
menu = []
num_of_ingredients = 10
count = 0
d = {}
for line in lines:
c = count % (num_of_ingredients + 1)
if c == 0:
print("Recipe name: ", line)
menu.append(d)
else:
l = line.split(' ')
print(l)
servings = l[0]
line = line[2::]
ingredient = line
print(servings, str(ingredient)) #this line was for me to know how it looks like
d[ingredient] = servings
count += 1
menu.append(d)
我猜您的文件格式是这样的[如果num_of_ingredients = 3]
Soup
1 cup flour
2 cup ginger
3 cup onion
Sandwitch
5 cup bread
3 cup meat
8 cup garlic
而你想要的是
[ {"Recipe name": "Soup", "flour":"1 cup", "ginger": "2 cups", "onion":"3 cup"}, ...]
该代码将帮助您:
with open(r"food.txt", "r") as f:
lines = f.readlines()
num_of_ingredients = 3
menu = []
d = {} #This defined here just to avoid some warning(d being used before being assigned).
for n_line, line in enumerate(lines):
if not ( n_line % (num_of_ingredients+1)): #enumerate is far better choice than counting manually
if (n_line != 0) :
menu.append(d) #dictionary will be appended , only when it is time to assign a new recipe(but you know that already)
d = {} #Here comes the important part(your answer), This is how you should assign new empty dict, everytime a new list item is initiated.
d["Recipe name"] = line
else:
ingredient = ' '.join(line.split()[2:])
servings = ' '.join(line.split()[:2])
d[ingredient] = servings
menu.append(d) #this last append is beacuse after the last iteration, we won't go back to the if block, to append rhe last list item.
print(menu)
如果我的假设有误,请告诉我。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句