如何以随机顺序迭代字典的所有项?我的意思是random.shuffle,但是对于字典。
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
你不能。使用.keys()
获取密钥列表,将它们随机播放,然后在索引原始字典时迭代列表。
或者使用.items()
,然后进行随机播放和迭代。
由于Charles Brunet已经说过字典是随机排列的键值对。但要使其真正随机,您将使用随机模块。我编写了一个将所有键重新排列的函数,因此当您迭代它时,您将随机迭代。通过查看代码,您可以更清楚地理解:
def shuffle(q):
"""
This function is for shuffling
the dictionary elements.
"""
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
return selected_keys
现在,当您调用该函数时,只需传递参数(您想要随机播放的字典的名称),您将获得一个洗牌的密钥列表。最后,您可以为列表的长度创建一个循环,并使用name_of_dictionary[key]
来获取值。
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()