Droxbot
Droxbot

Reputation: 53

Selecting a random value from a dictionary in python

Here is my function:

def evilSetup():
    words = setUp()
    result = {}
    char = input('Please enter your one letter guess: ')
    for word in words:
        key = ' '.join(char if c == char else '-' for c in word)
        if key not in result:
            result[key] = []
        result[key].append(word)
    return max(result.items(), key=lambda keyValue: len(keyValue[1]))

from collections import defaultdict
import random
words= evilSetup()#list of words from which to choose
won, lost = 0,0 #accumulators for games won, and lost
while True:
    wrongs=0 # accumulator for wrong guesses
    secretWord = words
    print(secretWord) #for testing purposes
    guess= len(secretWord)*'_'
    print('Secret Word:' + ' '.join(guess))
    while wrongs < 8 and guess != secretWord:
        wrongs, guess = playRound(wrongs, guess)
    won, lost = endRound(wrongs,won,lost)
    if askIfMore()== 'N':
            break
printStats(won, lost)

The function will take a list of words, and sort them into a dictionary based on the position of the guessed letter. As of now, it returns the key,value pair that is the largest. What I would like it to ultimately return is a random word from the biggest dictionary entry. The values as of now are in the form of a list.

For example {- - -, ['aah', 'aal', 'aas']}

Ideally I would grab a random word from this list to return. Any help is appreciated. Thanks in advance.

Upvotes: 0

Views: 972

Answers (1)

senshin
senshin

Reputation: 10360

If you have a list lst, then you can simply do:

random_word = random.choice(lst)

to get a random entry of the list. So here, you will want something like:

return random.choice(max(result.items(), key=lambda kv: len(kv[1]))[1])
#      ^^^^^^^^^^^^^^                                              ^^^^

Upvotes: 1

Related Questions