从python字典中删除项目给我错误

时间:2019-01-31 04:43:20

标签: python python-3.x dictionary

我正在学习python,并且认为开发游戏“ deal or no deal”的克隆会很有趣。我遇到了从我的案件判决书中删除案件的问题。它失败的一个关键错误。我试图在输入中将键设置为字符串,但这也失败了。

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)

2 个答案:

答案 0 :(得分:2)

您的键是数字str中的默认输入,因此您需要将其转换为int

变更输入线,如下:

yourCase = int(input('Select your case: '))

答案 1 :(得分:2)

您的键将是int中的enumerate 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)}