简体   繁体   English

Python:随机 Select 字典中所有键中的一个键

[英]Python: Randomly Select One Key From All Keys in a Dictionary

Let's say I have accessed my dictionary keys using print (hamdict.keys())假设我使用print (hamdict.keys())访问了我的字典键

Below is a sample output:下面是一个示例 output:

在此处输入图像描述

I know my dictionary list has a length of 552 elements.我知道我的字典列表有 552 个元素的长度。 I want to randomly select one "key" word from my list and assign it to the variable "starter".我想从我的列表中随机 select 一个“关键”词并将其分配给变量“starter”。 I tried to do this with the code below (note: I have a dictionary called hamdict):我尝试使用下面的代码执行此操作(注意:我有一本名为 hamdict 的字典):

random_num = random.randint(0, len(hamdict.keys())-1)
print (random_num)
print (hamdict.keys()[random_num])

I'm able to get a value for random_num so that seems to work.我能够获得 random_num 的值,因此这似乎可行。 But the second print returns the following error:但第二次打印返回以下错误:

在此处输入图像描述

How can I fix my code?如何修复我的代码?

my_dictionary.keys() returns a generator-like object, not a list. my_dictionary.keys()返回类似生成器的 object,而不是列表。 You can probably get what you want by converting it to a list first您可以通过先将其转换为列表来获得所需的内容

print(list(hamdict.keys())[random_num])

Try this:尝试这个:

random.sample(hamdict.keys(),1)[0]

The sample() function randomly selects a given number of items from a list or iterator. sample() function 从列表或迭代器中随机选择给定数量的项目。 Contrary to the choice function, it supports iterators so you don't need to make a list out of the keys beforehand.与选择 function 不同,它支持迭代器,因此您无需事先从键中列出列表。 The result is a list so you need to get its first item from the output (hence the [0] ).结果是一个列表,因此您需要从 output (因此[0] )中获取其第一项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM