简体   繁体   English

Python random.choice

[英]Python random.choice

Does anyone have an idea of how I can use random.choice on a python dictionary to choose a key from the dictionary.有没有人知道我如何在 python 字典上使用 random.choice 从字典中选择一个键。

Also, how do I integrate an if statement that checks whether the value that is entered from raw_input is assigned to the key that is randomly chosen?另外,如何集成 if 语句来检查从 raw_input 输入的值是否分配给随机选择的键?

import random
my_dict = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3', 'key4': 'val4'}
rand_key = random.choice(my_dict.keys())
user_input = raw_input('Guess...')

if user_input == my_dict[rand_key]:
    print 'You guessed it!'
else:
    print 'Better luck next time!'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM