Home > OS >  KeyError while retrieving random parameter from dictionary
KeyError while retrieving random parameter from dictionary

Time:06-29

So currently im working on a black jack game where cards are put in a dictionary and each starting deck has a random card taken from the dictionary but when i execute the code i get a keyerror

code

# Black Jack
import random
from art import logo
print(logo)
cards = {
    "ace": [1, 11],
    "one": 1,
    'two': 2,
    'three': 3,
    "four": 4,
    "Five": 5,
    "six": 6,
    'seven': 7,
    'eight': 8,
    'nine': 9,
    "king": 10,
    "queen": 10,
    "jack": 10,
    "ten": 10
}

user_deck = []
computer_deck = []
user_deck.append(random.choice(cards))
computer_deck.append(random.choice(cards))
print(f"{computer_deck} \n {user_deck}" )

CodePudding user response:

random.choice(seq) does

Return a random element from the non-empty sequence seq.

and you give it dict which is not sequence, you need first to convert keys of said dict into sequence, for example tuple that is replace

user_deck.append(random.choice(cards))
computer_deck.append(random.choice(cards))

using

user_deck.append(random.choice(tuple(cards.keys())))
computer_deck.append(random.choice(tuple(cards.keys())))

CodePudding user response:

Consider doing it in the following way:

user_deck.append(random.choice(tuple(cards.keys())))
computer_deck.append(random.choice(tuple(cards.keys())))

The problem is random.choice() accepts seq which has to support __getitem__() and __len__() methods, it should be list or tuple, not set or dict which you passed.

  • Related