首页 > 解决方案 > 您如何将用户的输入与提供的字典中的值进行比较?

问题描述

我一直在尝试将用户的输入与提供的字典中的值进行比较。

问题:

你的程序应该问你要花多少钱。然后,它应该使用我们提供的物品及其价格的字典来确定您有足够的钱购买哪些物品。

代码

wishlist = {
    'PS5': 750,
    'Phone case': 30,
    'Oodie': 90,
    'LEGO Hogwarts Castle': 650,
    'JBL Headphones': 130,
    'Drum kit': 520,
    'Phone recharge': 30,
    'Earrings': 110,
    'Spotify subscription': 60,
    'Hockey stick': 130,
    'Big Toblerone': 16,
    'Volleyball': 90,
    'Fitbit': 99,
    'Harry Potter box set': 65,
    'New Chucks': 70,
    }

money = int(input('How much money do you have to spend? '))
print('The presents you can afford are:')
for gifts in wishlist.keys():
    print(gifts)

我试图将投入的资金与物品的成本进行比较,并只输出投入金额可以承受的物品。

例如 演示

标签: pythonpython-3.x

解决方案


这应该工作

wishlist = {'PS5': 750, 'Phone case': 30, 'Oodie': 90, 'LEGO Hogwarts Castle': 650, 'JBL Headphones': 130, 'Drum kit': 520, 'Phone recharge': 30, 'Earrings': 110, 'Spotify subscription': 60, 'Hockey stick': 130, 'Big Toblerone': 16, 'Volleyball': 90, 'Fitbit': 99, 'Harry Potter box set': 65, 'New Chucks': 70}

money = int(input('How much money do you have to spend? '))
print('The presents you can afford are:')
for (item,value) in wishlist.items():
  if value <= money:
      print(item,value)

推荐阅读