[英]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.