从python Dict中删除项时出错
我正在学习python,并认为制作一个游戏“交易或无交易”的克隆版本会很有趣。我在从我的案件记录中删除一个案件时遇到了问题。它失败了,出现了一个密钥错误。我尝试在输入端将我的键设置为字符串,但也失败了从python Dict中删除项时出错,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我正在学习python,并认为制作一个游戏“交易或无交易”的克隆版本会很有趣。我在从我的案件记录中删除一个案件时遇到了问题。它失败了,出现了一个密钥错误。我尝试在输入端将我的键设置为字符串,但也失败了 import random # List of deal or no deal case amounts amounts = [0.1, 1, 5, 10, 25, 50, 75, 100, 200, 300, 400, 500, 750, 1000, 5000, 1000
import random
# List of deal or no deal case amounts
amounts = [0.1, 1, 5, 10, 25, 50, 75, 100, 200,
300, 400, 500, 750, 1000, 5000, 10000,
25000, 50000, 750000, 100000, 200000,
300000, 400000, 500000, 750000, 1000000]
# Randomize the amounts for the cases
random.shuffle(amounts)
# Check our amounts now..
print('current amount order:', amounts)
# Create cases dict with amounts in random order
cases = dict(enumerate(amounts))
# Check the new dict.
print('current cases:', cases)
# Have the player select their case
yourCase = input(str('Select your case: '))
# Remove the case the user selected from the cases dict
try:
del cases[yourCase]
except KeyError:
print('Key not found!')
# Our cases dict now...
print('Now cases are:', cases)
您的键是数值,并且是
str
中的默认输入,因此需要将其转换为int
更改输入行,如下所示:
yourCase = int(input('Select your case: '))
您的键是数值,并且是
str
中的默认输入,因此需要将其转换为int
更改输入行,如下所示:
yourCase = int(input('Select your case: '))
您的键将是
枚举
中的int
s,因此首先将输入转换为int
:
# Have the player select their case
yourCase = input('Select your case: ')
# Remove the case the user selected from the cases dict
try:
del cases[int(yourCase)]
except KeyError:
print('Key not found!')
except ValueError:
print('Invalid input!')
如果您希望您的dict
首先具有字符串键,可以执行以下操作:
# Create cases dict with amounts in random order
cases = {str(i): x for i, x in enumerate(amounts)}
您的键将是
枚举
中的int
s,因此首先将输入转换为int
:
# Have the player select their case
yourCase = input('Select your case: ')
# Remove the case the user selected from the cases dict
try:
del cases[int(yourCase)]
except KeyError:
print('Key not found!')
except ValueError:
print('Invalid input!')
如果您希望您的dict
首先具有字符串键,可以执行以下操作:
# Create cases dict with amounts in random order
cases = {str(i): x for i, x in enumerate(amounts)}