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

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

我该怎么做呢?


当前回答

这适用于Python 2和Python 3:

随机键:

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

一个随机值

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

一个随机键和值

random.choice(list(d.items()))

其他回答

下面是一个字典类的Python代码,它可以在O(1)时间内返回随机键。(为了可读性,我在代码中包含了myypy类型):

from typing import TypeVar, Generic, Dict, List
import random

K = TypeVar('K')
V = TypeVar('V')
class IndexableDict(Generic[K, V]):
    def __init__(self) -> None:
        self.keys: List[K] = []
        self.vals: List[V] = []
        self.dict: Dict[K, int] = {}

    def __getitem__(self, key: K) -> V:
        return self.vals[self.dict[key]]

    def __setitem__(self, key: K, val: V) -> None:
        if key in self.dict:
            index = self.dict[key]
            self.vals[index] = val
        else:
            self.dict[key] = len(self.keys)
            self.keys.append(key)
            self.vals.append(val)

    def __contains__(self, key: K) -> bool:
        return key in self.dict

    def __len__(self) -> int:
        return len(self.keys)

    def random_key(self) -> K:
        return self.keys[random.randrange(len(self.keys))]

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

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

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

在现代版本的Python中(从3开始),方法dict.keys(), dict.values()和dict.items()返回的对象是视图对象*。hey可以被迭代,所以直接使用random。选择是不可能的,因为现在他们不是一个列表或集合。

一种选择是使用列表理解来完成random.choice的工作:

import random

colors = {
    'purple': '#7A4198',
    'turquoise':'#9ACBC9',
    'orange': '#EF5C35',
    'blue': '#19457D',
    'green': '#5AF9B5',
    'red': ' #E04160',
    'yellow': '#F9F985'
}

color=random.choice([hex_color for color_value in colors.values()]

print(f'The new color is: {color}')

引用:

*Python 3.8:标准库文档-内置类型:字典视图对象 Python 3.8:数据结构-列表推导式

我写这篇文章是为了解决同样的问题:

https://github.com/robtandy/randomdict

它有O(1)对键、值和项的随机访问。

当他们要求随机配对时,他们指的是键和值。

对于这样一个字典,其中的关键:价值观是国家:城市,

使用random.choice()。

将字典键传递给这个函数,如下所示:

import random
keys = list(my_dict)
country = random.choice(keys)

你可能希望跟踪在一轮中已经被调用的键,当获得一个新的国家时,循环直到随机选择不在那些已经“抽取”的列表中……只要绘制的列表比键列表短。