我如何使用while循环在字典中添加任意数量的键和来自用户输入的多个值

问题描述 投票:-1回答:2
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循环可能会有所帮助,但我不确定。

提前感谢您的答复。

python dictionary input while-loop append
2个回答
0
投票
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)

这是您要寻找的吗?这只是继续添加字典,直到用户键入是。


0
投票

类似这样是根据您的期望的:

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)))

   if item1 in profit_dict.keys():
       profit_dict[item1]['good'].append(price_good)
       profit_dict[item1]['bad'].append(price_bad)

   else:
       profit_dict[item1]={'good':[price_good],'bad':[price_bad]}

   user_choice= input('Do you have anymore items: ')
   if user_choice in ['Yes','yes','y','Y']:
        pass
   else:
        break

=>您将得到字典的字典结果:{'Item1':{'good':[1,2,3],'bad':[0,0,1]},'Item2':{'good':[10,20,30],'bad ':[1,2,3]},,...,'ItemX':{'good':[10,20,30],'bad':[1,2,3]}}]

然后您可以尝试通过类似以下方式调用打印件:

print(f'This is your best profit outcome: {max(profit_dict[item]['good'])}')
print(f'This is your worst profit outcome: {min(profit_dict[item]['bad'])}')
© www.soinside.com 2019 - 2024. All rights reserved.