Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading