Search code examples
pythondictionarykeyerror

How to randomly select an item from a dictionary?


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


Solution

  • 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.