簡體   English   中英

隨機訪問 python 中的字典值

[英]randomly accessing dictionary values in python

所以我有代碼,它應該隨機選擇是向用戶顯示條目本身還是相關的定義。

from random import *


def show_flashcard():

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

glossary = {'word1':'definition1',
            'word2':'definition2',
            'word3':'definition3'}

它只顯示隨機鍵,但不顯示值。 我如何在我的代碼中實現這一點?

使用choice(list(glossary.values())) ,您可以從字典中獲取隨機值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM