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

Python 如何从一个键有多个值的字典中获取随机键值对?,python,tuples,Python,Tuples,我试图使用random.sample()返回一个随机的键值对,并只打印该键,即fruits:papaya,但我的代码返回一个TypeError。如何修复它?谢谢 import random Dictionary = {"fruits": ["watermelon","papaya", "apple"], "buildings": ["apartment", "mus

我试图使用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
random.sample(Dictionary.items(),2)
从字典中返回两个随机键值对,因此
hint
成为第一个键值对,而
selected\u word
成为第二个键值对。因此,提示是
(“水果”、“西瓜”、“木瓜”、“苹果”)
。由于无法连接字符串(
“提示:”
)和元组(
Hint
),因此您会得到该错误

是否只需要一个键值对?Do
hint,selected\u word=random.sample(Dictionary.items(),1)[0]

如果要打印一串下划线,并且关键字中每个单词有一个下划线,只需执行以下操作:
print(“\u”*len(selected\u 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']

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

在示例代码中,
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
包含键,
所选单词将包含值列表。

我在引用@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(),因为它已经被弃用了。

您的描述与您的代码不匹配:您想返回密钥(例如
水果
)还是值,加上
,例如
西瓜(木瓜)苹果
?@mcsoini我只想在其密钥中有一个值。该键将被打印,其值将被替换为
。为了清楚起见,我编辑了我的问题。是的,这就是我想要的。
[0]
是什么意思?
random.sample(Dictionary.items(),1)
给出了长度为1的键值对列表。因为您想获得键值对本身,所以需要选择列表中的第一个(也是唯一的)元素。@Kentta查看更新后的答案以了解更多简化信息。虽然第一个print语句没有问题,但代码在运行时只返回两个字母的值。@Kentta我不明白。请参阅更新后的答案,以获取此代码的输出。