How to iterate through dict in random order in Python?

前端 未结 5 1655
南笙
南笙 2020-12-11 00:31

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

5条回答
  •  失恋的感觉
    2020-12-11 01:14

    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.

提交回复
热议问题