I am creating a game: 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.