38

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!

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
beepretty
  • 1,075
  • 3
  • 14
  • 20

2 Answers2

64

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

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Binary Birch Tree
  • 15,140
  • 1
  • 17
  • 13
0

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