简体   繁体   English

如何在 Python 中按键检索字典值?

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

I am creating a game: Rock, Paper, Scissors, Lizard, Spock.我正在创建一个游戏:Rock, Paper, Scissors, Lizard, Spock。 The computer will prompt for a user choice and make one of its own.计算机将提示用户选择并做出自己的选择。 How can I display the value assigned to the dictionary key chosen by the computer?如何显示分配给计算机选择的字典键的值?

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'

Use the key chosen by the computer to access the value directly.使用计算机选择的键直接访问值。

# 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.

相关问题 在python中如何将字符串转换为字典以检索特定值 - In python how do I convert string to dictionary to retrieve a particular value Python:如何从字典键中随机选择一个值? - Python: How do I randomly select a value from a dictionary key? 如何在Python中汇总字典并按键值排序 - How do I Sum Dictionary in Python and Sort by Key Value 如何在python字典中附加键的值? - How do I append the value of a key in a python dictionary? 如何在 python 中打印字典的键值对 - How do I print the key-value pairs of a dictionary in python 如何忽略字典中键的相同值? (Python) - how do I ignore a same value of a key in dictionary? (Python) 在python中,我执行“ dictionary = {“ key”:[value,value],(etc)}”。如何在Visual Basic中做到这一点? - In python I do “dictionary = {”key“: [value, value], (etc)}” How do I do this in Visual Basic? 在 python 中为字典键添加了多个值。 如何检索指定的值? - Added multiple values to a dictionary key in python. How can I retrieve a specified value? Python-如何检索类似于字典的json字符串中与同一键关联的多个值? - Python- How do I retrieve the multiple values associated with the same key in a dictionary-like json string? 如何在python字典中检索给定键(即PosixPath类型的键)的值? - How do I retrieve values given a key (thats of type PosixPath) in a python dictionary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM