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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37153472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:57:49  来源:igfitidea点击:

How to pick one key from a dictionary randomly

pythondictionaryrandom

提问by beepretty

I am a beginner of Python. I try to use this method:

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

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!

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

回答by Binary Birch Tree

To choose a random key from a dictionary named my_dict, you can use:

要从名为 的字典中选择一个随机键my_dict,您可以使用:

random.choice(list(my_dict))

This will work in both Python 2 and Python 3.

这将适用于 Python 2 和 Python 3。

For more information on this approach, see: https://stackoverflow.com/a/18552025

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