How do I pull a random key from a dictionary with a certain value?

Question:

I have a dictionary of words, each of which with a certain point value. I would dictionary to search though this dictionary for a random word with a specific point value, i.e. find a random word with a point value of 3. my dictionary is structured like this:

wordList = {"to":1,"as":1,"be":1,"see":2,"bed":2,"owl":2,"era":2,"alive":3,"debt":3,"price":4,"stain":4} #shortened list obviously

Looked around online and I couldn’t find a great answer, that or I did and I just didn’t quite get it.

Asked By: taxEvader

||

Answers:

I would use random.choice() with a list comprehension:

from random import choice

choice([word for word, count in wordList.items() if count == 3])
Answered By: BrokenBenchmark

If you don’t care about performance, that will work but it will recreate a dictionary every time you access it:

random.choice([k for k,v in wordList.items() if v == 3])

otherwise it’s could be better to create a reversed dictionary, to save the time in multiple runs:

from random import choice
from collections import defaultdict
rev = defaultdict(list)
for k, v wordList.items():
    rev[v].append(k)

...

choice(rev[3])
Answered By: svfat

I think using if statement and random.choice answers your problem in a short time

from random import choice

wordList = {"to": 1, "as": 1, "be": 1, "see": 2, "bed": 2, "owl": 2, "era": 2,
            "alive": 3, "debt": 3, "price": 4, "stain": 4}  # shortened list obviously
value = int(input())
lst = []
for key,val in wordList.items():
    if val == value:
        lst.append(key)

print(choice(lst))

one-liner:

choice([key for key, val in wordList.items() if val == value])
Answered By: BGOPC
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.