How can I iterate through all items of a dictionary in a random order? I mean something random.shuffle, but for a dictionary.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
A
dict
is an unordered set of key-value pairs. When you iterate adict
, 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()
, anddict.values()
each return lists, which can be shuffled.Or, if you don't care about the keys:
You can also "sort by random":
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:
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. Hope this will add a value to this stack :)Source: Radius Of Circle
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.