How to pick one key from a dictionary randomly

Question:

I am a beginner of Python. I try to use this method:

random.choice(my_dict.keys())

but there is an error:

'dict_keys' object does not support indexing

my dictionary is very simple, like

my_dict = {('cloudy', 1 ): 10, ('windy', 1): 20}

Do you how to solve this problem? Thanks a lot!

Asked By: beepretty

||

Answers:

To choose a random key from a dictionary named my_dict, you can use:

random.choice(list(my_dict))

This will work in both Python 2 and Python 3.

For more information on this approach, see: https://stackoverflow.com/a/18552025

Answered By: Binary Birch Tree

like this,

import random
def get_random_key(d: typing.Dict):
    target_pos = random.randint(1, min(1000, len(d) - 1))
    for i, key in enumerate(d):
        if i == target_pos:
            return key
Answered By: WangShengguang
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.