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

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

我该怎么做呢?


当前回答

在现代版本的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:数据结构-列表推导式

其他回答

如果你不想使用随机模块,你也可以尝试popitem():

>> d = {'a': 1, 'b': 5, 'c': 7}
>>> d.popitem()
('a', 1)
>>> d
{'c': 7, 'b': 5}
>>> d.popitem()
('c', 7)

因为字典不保留顺序,所以使用popitem可以从字典中获得任意(但不是严格随机)顺序的项。

还要记住,popitem从字典中删除键值对,正如文档中所述。

Popitem()用于对字典进行破坏性迭代

因为这是家庭作业:

签出random.sample(),它将从列表中选择并返回一个随机元素。可以使用dict.keys()获得字典键列表,使用dict.values()获得字典值列表。

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

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

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

如果你不想使用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'
>>> import random
>>> d = dict(Venezuela = 1, Spain = 2, USA = 3, Italy = 4)
>>> random.choice(d.keys())
'Venezuela'
>>> random.choice(d.keys())
'USA'

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