如何从字典中随机选择一个键

时间:2016-05-11 05:02:26

标签: python dictionary random

我是Python的初学者。我尝试使用这种方法:

random.choice(my_dict.keys())

但是有一个错误:

'dict_keys' object does not support indexing

我的字典很简单,比如

my_dict = {('cloudy', 1 ): 10, ('windy', 1): 20}

你是如何解决这个问题的?非常感谢!

1 个答案:

答案 0 :(得分:31)

要从名为chown root:shell seed_generator.sh chmod 777 seed_generator.sh chown root:shell init.rc chmod 750 init.rc 的词典中选择随机密钥,您可以使用:

my_dict

这适用于Python 2和Python 3。

有关此方法的详细信息,请参阅:https://stackoverflow.com/a/18552025

相关问题