Bill
Bill

Reputation: 123

Removing items form a python Dict giving me error

I'm learning python and thought it'd be fun to work on a clone of the game "deal or no deal". I'm running into a problem removing a case from my dict of cases. It fails with a key error. I tried making my key a string at the input, but that fails too.

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)

Upvotes: 0

Views: 52

Answers (2)

iz_
iz_

Reputation: 16613

Your keys will be ints from the enumerate, so convert the input to an int first:

# 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!')

If you want your dict to have string keys in the first place, you can do this:

# Create cases dict with amounts in random order
cases = {str(i): x for i, x in enumerate(amounts)}

Upvotes: 2

Sociopath
Sociopath

Reputation: 13401

Your keys are numeric and default input in str, so you need to convert it into int.

Change your input line as below:

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

Upvotes: 2

Related Questions