首页 > 解决方案 > Calling methods and iterating over list

问题描述

I'm trying to ask for ingredients in a recipe via the input function. I want to store that ingredient in a dictionary, separated by quantity and ingredient. For example, an input of '3 eggs', should yield {'3': 'eggs'}.

The way i do this is with the separate() and convert_to_dict() methods. I want to ask continuously for the ingredients by means of the input, hence the while True loop. Basically, i do this via the following code:


ingredients_list = []


def separate(list):
    for i in list:
        return re.findall(r'[A-Za-z]+|\d+', i)


def convert_to_dict(list):
    i = iter(list)
    dct = dict(zip(i, i))
    return dct


while True:
    ingredient = input("Please input your ingredient: ")

    ingredients_list.append(ingredient)

    print(convert_to_dict(separate(ingredients_list)))

This works fine, but the only problem with it is that when i input another ingredient, the separate() and convert_to_dict() methods only seem to work for the first ingredient in the ingredient list. For example, i firstly input '3 eggs', and then '100 gr of flour', yet it only returns {'3': 'eggs'}. I'm sure there is something i'm missing, but can't figure out where it goes wrong.

标签: pythonlistdictionary

解决方案


I think you've got the idea of your key-value pairs the wrong way around!
Keys are unique. Updating a dictionary with an existing key will just override your value. So if you have 3 eggs, and 3 cups of sugar, how do you envision your data structure capturing this information?
Rather try doing -

{'eggs': 3}  # etc.

That should sort out a lot of problems...

But that's all besides the point of your actual bug. You've got a return in your for-loop in the separate function...This causes the function to return the first value encountered in the loop, and that's it. Once a function's reached a return in exist the function and returns to the outer scope.


推荐阅读