我如何从字典中得到一个随机对?我正在制作一款游戏,玩家需要猜测一个国家的首都,我需要随机出现问题。

字典看起来像{'VENEZUELA':'CARACAS'}

我该怎么做呢?


当前回答

如果你不想使用random.choice(),你可以尝试这样做:

>>> list(myDictionary)[i]
'VENEZUELA'
>>> myDictionary = {'VENEZUELA':'CARACAS', 'IRAN' : 'TEHRAN'}
>>> import random
>>> i = random.randint(0, len(myDictionary) - 1)
>>> myDictionary[list(myDictionary)[i]]
'TEHRAN'
>>> list(myDictionary)[i]
'IRAN'

其他回答

我需要遍历字典中的键的范围,而不是每次都对它排序,并找到了Sorted Containers库。我发现这个库可以通过索引随机访问字典项,直观地解决了这个问题,而不用每次都遍历整个字典:

>>> import sortedcontainers
>>> import random
>>> d = sortedcontainers.SortedDict({1: 'a', 2: 'b', 3: 'c'})
>>> random.choice(d.items())
(1, 'a')
>>> random.sample(d.keys(), k=2)
[1, 3]

我假设你在做一个类似测验的应用程序。对于这种应用程序,我写了一个函数,如下所示:

def shuffle(q):
"""
The input of the function will 
be the dictionary of the question
and answers. The output will
be a random question with answer
"""
selected_keys = []
i = 0
while i < len(q):
    current_selection = random.choice(q.keys())
    if current_selection not in selected_keys:
        selected_keys.append(current_selection)
        i = i+1
        print(current_selection+'? '+str(q[current_selection]))

如果我将输入问题={'委内瑞拉':'加拉加斯','加拿大':'多伦多'},并调用函数shuffle(问题),那么输出将如下:

VENEZUELA? CARACAS
CANADA? TORONTO

您还可以通过调整选项进一步扩展此功能

因为最初的帖子想要一对:

import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'}
country, capital = random.choice(list(d.items()))

(python 3风格)

这适用于Python 2和Python 3:

随机键:

random.choice(list(d.keys()))

一个随机值

random.choice(list(d.values()))

一个随机键和值

random.choice(list(d.items()))
>>> import random
>>> d = dict(Venezuela = 1, Spain = 2, USA = 3, Italy = 4)
>>> random.choice(d.keys())
'Venezuela'
>>> random.choice(d.keys())
'USA'

通过随机调用。选择字典的键(国家)。