Search code examples
pythondictionarylookup-tablesplaying-cardsblackjack

Lookup Table for BlackJack Deck of Cards


I'm making a simple blackjack game that works perfectly -- until it comes to adding the face cards into the deck. This lookup table returns: KeyError: 1

I know (or at least am pretty sure) it's because of: 'rank': self.values[face]

Why does it return KeyError: 1 ? And how can this be fixed?

import random

class DeckOfCards(object):
def __init__(self):
    self.values = {"2": 2,
                   "3": 3,
                   "4": 4,
                   "5": 5,
                   "6": 6,
                   "7": 7,
                   "8": 8,
                   "9": 9,
                   "10": 10,
                   "J": 10,
                   "Q": 10,
                   "K": 10,
                   "A": 11,
                   }
    self.faces = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']
    self.suits = ['C', 'D', 'H', 'S']
    self.unused_cards = []
    for suit in self.suits:
        for face in self.faces:
            self.unused_cards.append({'face': face, 'suit': suit, 'rank': self.values[face]})
    random.shuffle(self.unused_cards)
    self.used_cards = []

def play(self):
    print self.unused_cards

cardsss = DeckOfCards()
cardsss.play()

Solution

  • At this line, you are trying to access a key in the self.values dictionary that doesn't exist, because you have a self.face entry for '1' but you don't have a key in self.values for '1'.

    self.unused_cards.append({'face': face, 'suit': suit, 'rank': self.values[face]})