如何从字典中获取随机值? [英] How to get a random value from dictionary?
本文介绍了如何从字典中获取随机值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从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'}
我该怎么做?
推荐答案
一种方法是:
import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'}
random.choice(list(d.values()))
编辑:该问题在原始帖子发布后的几年内已更改,现在要求配对,而不是单个项目.现在最后一行应该是:
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()))
这篇关于如何从字典中获取随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文