3

I'm a python beginner trying to make a game of blackjack, and have been continuously getting multiple keyerrors regarding this code

def rank(rank):
    rank={
        '2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'Jack':10,
       'King':10,'Queen':10,'Ace':1}
    return random.choice(rank)

The error occurs when I try calling the function like this

def draw_card(card):
    card_rank=Card.rank(rank)
    card_suit=Card.suit(suit)
    card={card_suit:card_rank}
    return card

to try and use the 'rank' function in class 'Card' to apply attributes to a new 'card' variable

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
Darya Riazati
  • 33
  • 1
  • 4
  • 4
    Why are you calling `random.choice` on a dict, and why is everything in the `rank` function named `rank`? – user2357112 Jul 20 '18 at 20:58
  • 4
    You should make a `Card` class, instantiate 52 `Card` objects in a list, and then [`random.shuffle`](https://docs.python.org/3/library/random.html#random.shuffle) it. – Patrick Haugh Jul 20 '18 at 20:59
  • 2
    Possible duplicate of [How to get a random value in python dictionary](https://stackoverflow.com/questions/4859292/how-to-get-a-random-value-in-python-dictionary) – Engineero Jul 20 '18 at 21:02
  • 5
    Is this the exact code you are trying to run? Because it's full of syntactical and logical errors. – Gudarzi Jul 20 '18 at 21:02

1 Answers1

7

random.choice takes a list (or tuple) in input (it needs integer-indexable objects).

So just convert rank dictionary (the values, it is) to a list then pick a value: like this (I've created a new function because the rank(rank) bit made no sense, you don't need a parameter to pick a card:

# globally defined (constant), pointless to define it locally, you may
# need it in another part of the program
rank={'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'Jack':10,
   'King':10,'Queen':10,'Ace':1}

def pick():       
    return random.choice(list(rank.values()))

list(rank.values()) is required in python 3, dictionary values are no longer of list type. Maybe you want to pre-compute this list to save computation time.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • 1
    Even with the `list` call, the fact that a dict is involved at all is pointless, and generating new random cards on demand is probably inappropriate in the first place. – user2357112 Jul 20 '18 at 21:04
  • yep, but the dict may be used somewhere else, I made it global – Jean-François Fabre Jul 20 '18 at 21:04
  • Thank you, this has been helpful. I do need the rank as a dictionary, though, so that I can return to the user the rank+suit of their card (e.g. "Ace of Spades") and keep the blackjack value of each card assigned to it's name. – Darya Riazati Jul 20 '18 at 21:25