如何从一个键有多个值的字典中获取随机键值对?

2024-05-16 18:12:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用random.sample()返回一个随机的键值对,并只打印该键,即fruits:papaya,但我的代码返回一个TypeError。如何修复它?谢谢

import random

Dictionary = {"fruits": ["watermelon","papaya", "apple"], "buildings": ["apartment", "museum"], "mammal": ["horse", "giraffe"], "occupation": ["fireman", "doctor"]}


def choose_word():
    hint, chosen_word = random.sample(Dictionary.items(), 2)
    print("Hint: " + hint)
    blank = []
    for letter in chosen_word:
        blank.append("_")
    print("".join(blank))
    return chosen_word

错误消息

TypeError: can only concatenate str (not "tuple") to str

Tags: sample代码importdictionaryrandomword键值print
3条回答

random.sample(Dictionary.items(), 2)从字典返回两个随机键值对,因此hint成为第一个键值对,而chosen_word成为第二个键值对。因此,提示是('fruits', ['watermelon', 'papaya', 'apple'])。由于无法连接字符串("Hint: ")和元组(hint),因此会出现该错误

是否只需要一个键值对?Dohint, chosen_word = random.sample(Dictionary.items(), 1)[0]

如果您想打印一个下划线字符串,在关键字中每个单词有一个下划线,只需执行以下操作:print("_" * len(chosen_word))

因此,总体而言:

import random

Dictionary = {"fruits": ["watermelon","papaya", "apple"], 
              "buildings": ["apartment", "museum"], 
              "mammal": ["horse", "giraffe"], 
              "occupation": ["fireman", "doctor"]}

def choose_word():
    hint, chosen_word = random.sample(Dictionary.items(), 1)[0]
    print("Hint: " + hint)      
    print("_" * len(chosen_word))
    return chosen_word

choose_word()

印刷品:

Hint: mammal
__

返回:

Out[2]: ['horse', 'giraffe']

在引用了@Yogaraj和@mcsoini之后,我找到了一个解决方案

import random


Dictionary = {"fruits": ["watermelon", "papaya", "apple"],
              "buildings": ["apartment", "museum"],
              "mammal": ["horse", "giraffe"],
              "occupation": ["fireman", "doctor"]}


def choose_word():
    hint, chosen_words = random.choice(list(Dictionary.items()))
    print("Hint: " + hint)
    chosen_word = random.choice(list(chosen_words))
    print("_" * len(chosen_word))
    return chosen_word

它有点长,但它设法避免使用random.sample(),因为它已被弃用

根据random.sample的文档,它将返回从填充序列或集合中选择的唯一元素列表

在示例代码中,random.sample(Dictionary.items(), 2)将返回一个长度为2的列表

In [1]: random.sample(Dictionary.items(), 2)                                                                                                                                                  
Out[1]: [('occupation', ['fireman', 'doctor']), ('mammal', ['horse', 'giraffe'])]

您需要将random.sample方法的参数从2更改为1,并在展开时

hint, chosen_word = random.sample(Dictionary.items(), 1)[0]

hint包含键,chosen_word将包含值列表

相关问题 更多 >