在字典中查找值,而不是键

时间:2019-07-16 20:32:55

标签: python

我需要程序从字典中选择一个随机值,然后询问用户密钥是什么。字典是一个词汇表。我希望程序首先给用户一个定义。

4 个答案:

答案 0 :(得分:0)

您可以采用的一种方法是先从字典中获取随机密钥,然后再简单地获取值。为此,您可以使用random库,然后执行以下操作:

import random

glossary = {
    "water": "a transparent, odorless, tasteless liquid, a compound of hydrogen and oxygen",
    "wind": "air in natural motion",
    "fire": "a state, process, or instance of combustion in which fuel or other material is ignited and combined with oxygen"
}

correctAnswers = 0
totalQuestions = len(glossary)
while correctAnswers < totalQuestions:
    # Get a random key and value from the glossary dictionary
    word = random.choice(list(glossary.keys()))
    definition = glossary[word]

    # Present the prompt
    print("The definition is:", definition)
    answer = input("What word is this? ")

    # Determine if answer was correct
    if answer.lower() == word:
        print("Correct!")
        correctAnswers += 1
        del glossary[word]
    else:
        print("Incorrect, try again.")

这将从词汇表中输出一个随机定义,还将给出其映射依据。然后它将提示用户回答他们认为的单词是什么。如果它们是正确的,则将从词汇表中删除该定义,并询问是否仍然存在另一个问题。

希望这可以帮助您开始尝试做的事情。

答案 1 :(得分:0)

这是我想出的:

import random
d = {'Key 1':'Value 1', 'Key 2':'Value 2'}
randomKey = random.choice(list(d.keys()))
print(d[randomKey])

打印随机值。希望这会有所帮助。

编辑: 您复制的代码错误,应显示为:

random_key = random.choice(list(glossary))
print('Define: ', glossary[random_key])
input('Press return to see the definition')
print(glossary[random_key])

确保您已导入随机import random

答案 2 :(得分:0)

我建议这样做:

import numpy as np
dict = {"cat" : "a carnivorous mammal (Felis catus) long domesticated as a pet and for catching rats and mice.",
        "dog" : "A domesticated carnivorous mammal (Canis familiaris syn. Canis lupus subsp. familiaris) occurring as a wide variety of breeds, many of which are traditionally used for hunting, herding, drawing sleds, and other tasks, and are kept as pets.",
        "butterfly" : "Any of numerous insects of the order Lepidoptera, having four broad, usually colorful wings, and generally distinguished from the moths by having a slender body and knobbed antennae and being active during the day."}

length_dict = len(dict)
list_values = list(dict.values())
list_keys = list(dict.keys())
while True:
    r = np.random.randint(length_dict)
    print("Define: ")
    print(list_values[r])
    inp = input()
    if inp == list_keys[r]:
        print("Correct")

    else:
        print("Wrong")

答案 3 :(得分:0)

MDN Python不支持通过dict的值来检索键,因为无法保证这些值是唯一的。但是,如果将它们翻转(定义是关键,单词是值),则操作起来会容易得多。

You can't.到类似的问题,您可以使用python的随机库以及一些数据操作。

要获取python字典键的列表,可以使用list(yourDict.keys()-然后,可以使用random.choice()库中的random来获得随机键。最后,您可以使用此随机密钥作为d[]的索引,以获得结果。

import random
d = {'An aquatic animal':'FISH', 'A common pet':'DOG'}
question = random.choice(list(d.keys()))
val = d[question]
print(question)
print(val)

this answer

请注意,对于上面的示例,如果您确实想将单词存储为键,则可以设置val = random.choice(list(d.keys)))question = d[val]