Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 691
beepretty Avatar asked May 11 '16 05:05

beepretty


People also ask

How can I randomly select an item from a list?

randrange() Method to Randomly Select Elements From a List. This method is used to generate a random number in a range, for lists, we can specify the range to be 0 to its length, and get the index, and then the corresponding value.

How do you randomize a dictionary in Python?

Python dictionary is not iterable. Hence it doesn't have index to be randomized. Instead collection of its keys is iterable and can be randomized by shuffle() function in random module.

How do you separate a key from a value in a dictionary?

Creating a Dictionary To do that you separate the key-value pairs by a colon(“:”). The keys would need to be of an immutable type, i.e., data-types for which the keys cannot be changed at runtime such as int, string, tuple, etc. The values can be of any type.


1 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

like image 189
Binary Birch Tree Avatar answered Oct 02 '22 16:10

Binary Birch Tree