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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With