Python: Store a two-item list as a value in a dictionary from user input?
我正在尝试构建一个简单的杂货助手程序,它将作为输入
a)成分b)数值c)测量(例如,tb、cups)
最终将返回所需项目的列表。
因为我想允许用户输入同一种成分两次,然后将测量值添加到之前输入的成分中,所以我想知道如何将用户的数值和测量值以两项列表的形式存储为字典的值,以便以后可以修改这些值,然后全部打印出来。
以下是我为使主钻头正常工作所做的粗略尝试:
1 2 3 4 5 6 7 8 9 10 11 12 | ingredients = {} program_run = True while program_run: ingredient = input("Give me an ingredient:") measurement = input("Unit of measurement?") howMuch = input("How much?") ingredients[ingredient] = howMuch print(ingredients) |
那么,我如何才能让用户输入
1 | {"coriander": [2,"tsp"],"basil": [.5,"cups"]} |
谢谢您!
您需要从
1 2 3 4 5 6 7 8 9 10 11 12 | ingredients = {} program_run = True while program_run: ingredient = input("Give me an ingredient:") measurement = input("Unit of measurement?") howMuch = input("How much?") ingredients[ingredient] = [howMuch, measurement] print(ingredients) |
如果你想更好地格式化它,你可以这样做。
1 2 3 4 5 6 7 8 9 10 11 12 | ingredients = {} program_run = True while program_run: ingredient = input("Give me an ingredient:") symbol = input("Unit of measurement?") measurement = input("How much?") ingredients[ingredient] = [measurement, symbol] print(ingredients) |
好吧,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | ingredients = {} program_run = True while program_run: ingredient = input("Give me an ingredient:") measurement = input("Unit of measurement?") howMuch = input("How much?") # cast measurement to float and create a list from user inputs details = [float(measurement), howMuch] # add the list to the dict ingredients[ingredient] = details |