如何在Python中随机遍历字典?

24 投票
5 回答
25020 浏览
提问于 2025-04-17 04:26

我想知道怎么能以随机的顺序遍历字典里的所有项目。也就是说,我想要一种像 random.shuffle 这样的功能,但适用于字典。

5 个回答

0
import random

def main():

    CORRECT = 0

    capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau',
        'Arizona': 'Phoenix', 'Arkansas': 'Little Rock'} #etc... you get the idea of a dictionary

    allstates = list(capitals.keys()) #creates a variable name and list of the dictionary items
    random.shuffle(allstates) #shuffles the variable

    for a in allstates: #searches the variable name for parameter
        studentinput = input('What is the capital of '+a+'? ')
        if studentinput.upper() == capitals[a].upper():
            CORRECT += 1
main()

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

6

你不能直接这样做。你可以先用 .keys() 获取字典里的所有键,把它们打乱顺序,然后再通过这个打乱后的列表来访问原来的字典。

或者你也可以使用 .items(),先把键值对打乱顺序,然后再遍历这个打乱后的列表。

36

一个 dict(字典)是一个无序的键值对集合。当你遍历一个 dict 时,得到的顺序实际上是随机的。不过,如果你想要明确地随机化这些键值对的顺序,就需要使用一个有序的对象,比如列表。dict.items()dict.keys()dict.values() 都会返回列表,这些列表是可以打乱顺序的。

items=d.items() # List of tuples
random.shuffle(items)
for key, value in items:
    print key, value

keys=d.keys() # List of keys
random.shuffle(keys)
for key in keys:
    print key, d[key]

或者,如果你不在乎键的话:

values=d.values() # List of values
random.shuffle(values) # Shuffles in-place
for value in values:
    print value

你也可以“按随机排序”:

for key, value in sorted(d.items(), key=lambda x: random.random()):
    print key, value

撰写回答