【问题标题】:How to use random module on dictionaries in python 3? [duplicate]如何在 python 3 中的字典上使用随机模块? [复制]
【发布时间】:2021-12-04 08:47:34
【问题描述】:
from tkinter import Tk, simpledialog, messagebox
import random
Countries, Capitals = {'Belgium':'Brussels','France':'Paris', 'Germany':'Berlin', 'Italy':'Rome', 'Poland':'Warsaw'}
QueryCountry = simpledialog.askstring("What is the capital of " + )

我想制作一个程序,可以使用 Tkinter 对世界各国的首都进行测验。我想知道您是否可以在字典中使用随机模块。如果是的话,你能帮帮我吗?我是编码初学者,所以请帮忙。

【问题讨论】:

标签: python python-3.x dictionary random


【解决方案1】:

从 Python 字典中随机选择键的一种方法如下:

import random
Capitals = {'Belgium':'Brussels','France':'Paris', 'Germany':'Berlin', 'Italy':'Rome', 'Poland':'Warsaw'} 
key = random.choice(list(Capitals.keys()))
print(f'Key = {key}, value = {Capitals[key]}')

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 2013-11-17
    • 2013-06-07
    • 1970-01-01
    • 2013-09-16
    • 2015-04-26
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多