如何从字典中随机选择一个键 [英] How to pick one key from a dictionary randomly
本文介绍了如何从字典中随机选择一个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Python的初学者.我尝试使用这种方法:
I am a beginner of Python. I try to use this method:
random.choice(my_dict.keys())
但是有一个错误:
'dict_keys' object does not support indexing
我的字典很简单,就像
my_dict = {('cloudy', 1 ): 10, ('windy', 1): 20}
您如何解决此问题?非常感谢!
Do you how to solve this problem? Thanks a lot!
推荐答案
要从名为my_dict
的字典中选择随机密钥,可以使用:
To choose a random key from a dictionary named my_dict
, you can use:
random.choice(list(my_dict))
这将在Python 2和Python 3中都可用.
This will work in both Python 2 and Python 3.
有关此方法的更多信息,请参见: https://stackoverflow.com/a/18552025
For more information on this approach, see: https://stackoverflow.com/a/18552025
这篇关于如何从字典中随机选择一个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文