python - 如何使用 while 循环从用户输入中附加任意数量的键和多个值的字典
问题描述
print('Scenario Analysis')
profit_dict = {}
while True:
item1= input ('What is the item: ')
price_good= int (input('What is the expected profit of {}, in the best case scenario: '.format(item1)))
price_bad = int( input ('What is the expected profit of {}, in the worst case scenario: '.format(item1)))
user_choice= input('Do you have anymore items: ')
if user_choice in ['Yes','yes','y','Y']:
pass
else:
break
profit_dict[item1]=price_good,price_bad
#EVERYTHING FROM HERE ON IS NOT RELEVANT DIRECTLY TO QUESTION BUT PROVIDES CONTEXT
print('This is your best profit outcome: ')
for values in good_dict.values():
total_list=(max(values))
print(total_list)
print('This is your worst profit outcome: ')
我知道变量的使用将不断取代字典,但这是我可以展示我的目标的最佳方式。可能使用函数而不是 while 循环可能会有所帮助,但我不确定。
提前感谢您的任何回复。
解决方案
profit_dict = {}
while True:
item1= input ('What is the item: ')
price_good= int (input('What is the expected profit of {}, in the best case scenario: '.format(item1)))
price_bad = int( input ('What is the expected profit of {}, in the worst case scenario: '.format(item1)))
user_choice= input('Do you have anymore items: ')
profit_dict[item1]=[price_good,price_bad]
if user_choice in ['Yes','yes','y','Y']:
continue
else:
break
print(profit_dict)
这是你想要的 ?这只是继续添加字典,直到用户输入是。