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

时间:2021-04-25 07:26:33

标签: python tuples

我正在尝试使用 random.sample() 返回一个随机键值对,并仅打印键,即水果:木瓜,但我的代码返回一个 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

3 个答案:

答案 0 :(得分:1)

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

您是否只想要一个键值对?做hint, 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']

答案 1 :(得分:1)

根据 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 将包含值列表。

答案 2 :(得分:0)

参考@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() 因为它无论如何都被弃用了。