Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through dict in random order in Python?

Tags:

How can I iterate through all items of a dictionary in a random order? I mean something random.shuffle, but for a dictionary.

like image 591
Charles Brunet Avatar asked Oct 16 '11 16:10

Charles Brunet


People also ask

How do I randomize a dictionary order in Python?

Shuffle a Dictionary in Python Shuffling a dictionary is not possible in Python. However, we can rearrange the order of keys of a dictionary. Fetch all keys from a dictionary as a list. Shuffle that list and access dictionary values using shuffled keys.

Does Python iterate through dictionary in order?

With Python 3.7, a dictionary is guaranteed to be iterated in the insertion order of keys. If you need to iterate over a dictionary in sorted order of its keys or values, you can pass the dictionary's entries to the sorted() function, which returns a list of tuples.

How do you iterate through a dictionary list?

To iterate through the dictionary's keys, utilise the keys() method that is supplied by the dictionary. An iterable of the keys available in the dictionary is returned. Then, as seen below, you can cycle through the keys using a for loop.


2 Answers

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 
like image 94
Austin Marshall Avatar answered Sep 28 '22 14:09

Austin Marshall


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.

like image 21
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 14:09

Ignacio Vazquez-Abrams