【问题标题】:Finding a value in a dictionary, not a key在字典中查找值,而不是键
【发布时间】:2019-11-25 15:33:35
【问题描述】:

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

【问题讨论】:

标签: python


【解决方案1】:

解决此问题的一种方法是先从字典中获取一个随机键,然后再简单地检索该值。为此,您可以使用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.")

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

希望这能让您开始尝试做的事情。

【讨论】:

  • 如果你看一下上面的例子,它会为你获取单词和定义。因此,您可以选择要显示的内容。
  • 我编辑了我的答案以解决问题的每个部分。总之,程序会为每个问题随机选择一个定义并继续循环,直到词汇表中的所有定义都得到正确回答。
【解决方案2】:

这是我想出的:

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

【讨论】:

  • 应该是random_key = random.choice(list(glossary))
  • 其实应该是:random_key = random.choice(list(glossary))print('Define: ', glossary[random_key])input('Press return to see the definition')print(glossary[random_key])
  • 你改变主意了吗?这是你写的:我希望程序给用户一个定义,然后用户猜这个词。
【解决方案3】:

You can't. Python 不支持通过值从字典中检索键,因为无法保证值是不同的。但是,如果你翻转它们(定义是关键,词是价值),它会更容易做到。

this answer到类似的问题,可以使用python的随机库,再加上一点数据操作。

要获取 python 字典的键列表,您可以使用 list(yourDict.keys() - 然后,您可以使用 random 库中的 random.choice() 来获取随机键。最后,您可以使用这个随机键作为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)

Try it here!

请注意,对于上面的例子,如果你真的想存储单词作为key,你可以设置val = random.choice(list(d.keys)))question = d[val]

【讨论】:

  • 我认为您可能想要这样做,并将其包含在我的答案中。找到一个随机键也意味着你找到了一个随机值,所以如果你将一个随机键存储在一个变量中并向用户呈现d[key],这与向他们呈现一个随机值是一样的。 Randomly selecting a value and then finding its key is not possible in python,因为值不能保证是唯一的。
  • 为此,您只需切换打印顺序。先是print('Define:', glossary[random_value]),然后是print(random_value),当他们按下回车键时。
  • 你认为保持第一行不变就可以了吗? random_value = 选择(列表(词汇表))?
  • 是的,保持第一行不变就可以了。 random_value 仍然包含一个 key,因为 list(glossary) 返回一个键列表,但代码将按照您的预期运行。
【解决方案4】:

我建议这样做:

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")

【讨论】:

  • 这是一个很好的方法,但我会改变一些事情。首先,列表中的顺序永远无法保证,所以我会使用元组。其次,我会这样做,所以答案不区分大小写。所以你最终得到if inp.lower() == list_keys[r].lower():
  • order in a list is never guaranteed 是的。这是一个列表。从字面上看,一个有序的有限集。你可能会想到 Python 的 set 数据类型。
猜你喜欢
  • 2021-12-11
  • 2019-08-06
  • 1970-01-01
  • 2015-08-05
  • 1970-01-01
  • 1970-01-01
  • 2018-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多