如何从python中的字典中获取随机值 [英] How to get a random value from dictionary in python
本文介绍了如何从python中的字典中获取随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从dict
中获得随机对?我正在制作一款游戏,您需要猜测一个国家的首都,并且需要随机出现的问题.
How can I get a random pair from a dict
? I'm making a game where you need to guess a capital of a country and I need questions to appear randomly.
dict
看起来像{'VENEZUELA':'CARACAS'}
我该怎么做?
推荐答案
一种方法(在Python 2. *中)是:
One way (in Python 2.*) would be:
import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'}
random.choice(list(d.keys()))
编辑:该问题在原始帖子发布后的几年内已更改,现在要求配对,而不是单个项目.现在最后一行应该是:
EDIT: The question was changed a couple years after the original post, and now asks for a pair, rather than a single item. The final line should now be:
country, capital = random.choice(list(d.items()))
这篇关于如何从python中的字典中获取随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文