beepretty
beepretty

Reputation: 1127

How to pick one key from a dictionary randomly

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!

Upvotes: 40

Views: 56291

Answers (2)

WangShengguang
WangShengguang

Reputation: 11

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

Upvotes: 0

Binary Birch Tree
Binary Birch Tree

Reputation: 15728

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

Upvotes: 66

Related Questions