簡體   English   中英

如何在 Python 中按鍵檢索字典值?

[英]How do I retrieve a dictionary value by key in Python?

我正在創建一個游戲:Rock, Paper, Scissors, Lizard, Spock。 計算機將提示用戶選擇並做出自己的選擇。 如何顯示分配給計算機選擇的字典鍵的值?

def play ():
    user = input("Choose 'r' for Rock, 'p' for Paper, 's' for Scissors, 'l' for Lizzard, 'm' for 'Mr.' Spock: ")
    #Key is abbriviation and the value is the name of the item chosen by the computer
    rpslm = {'r':'rock', 'p':'paper', 's':'scissors', 'l':'lizard', 'm':'Spock'}
    computer = random.choice(list(rpslm.keys()))
    
    choose = #want to display the value here so that the value can be displayed in the answers
    
    

    if user == computer:
        return f'Computer\'s choice was \'{choose}\'. It\'s a tie'
    
    #Scissors cuts Paper, Paper covers Rock, 
    #Rock crushes Lizard, Lizard poisons Spock, Spock smashes Scissors
    #Scissors decapitates Lizard, Lizard eats Paper, Paper disproves Spock,
    #Spock vaporizes Rock, and as it always has, Rock crushes Scissors
    
    if is_win(user, computer):
        return f'Computer\'s choice was \'{choose}\'. You Won!'
    
    return f'Computer\'s choice was \'{choose}\'. You lost'

使用計算機選擇的鍵直接訪問值。

# Bonus: dict.keys() returns a list; there is no need to convert it to a list again
computer = random.choice(rpslm.keys())

# Dictionary values can be accessed using the key as follows...
choose = rpslm[computer]

暫無
暫無

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

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