How can I iterate through all items of a dictionary in a random order? I mean something random.shuffle, but for a dictionary.
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()
As Charles Brunet have already said that the dictionary is random arrangement of key value pairs. But to make it really random you will be using random module. I have written a function which will shuffle all the keys and so while you are iterating through it you will be iterating randomly. You can understand more clearly by seeing the code:
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
Now when you call the function just pass the parameter(the name of the dictionary you want to shuffle) and you will get a list of keys which are shuffled. Finally you can create a loop for the length of the list and use name_of_dictionary[key]
to get the value.
A dict
is an unordered set of key-value pairs. When you iterate a dict
, it is effectively random. But to explicitly randomize the sequence of key-value pairs, you need to work with a different object that is ordered, like a list. dict.items()
, dict.keys()
, and dict.values()
each return lists, which can be shuffled.
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]
Or, if you don't care about the keys:
values=d.values() # List of values
random.shuffle(values) # Shuffles in-place
for value in values:
print value
You can also "sort by random":
for key, value in sorted(d.items(), key=lambda x: random.random()):
print key, value
You can't. Get the list of keys with .keys()
, shuffle them, then iterate through the list while indexing the original dict.
Or use .items()
, and shuffle and iterate that.
I wanted a quick way for stepping through a shuffled list, so I wrote a generator:
def shuffled(lis):
for index in random.sample(range(len(lis)), len(lis)):
yield lis[index]
Now I can step through my dictionary d
like so:
for item in shuffled(list(d.values())):
print(item)
or if you want to skip creating a new function, here is a 2-liner:
for item in random.sample(list(d.values()), len(d)):
print(item)