How to pick one key from a dictionary randomly

2020-02-20 06:51发布

问题:

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!

回答1:

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