How to iterate through dict in random order in Python?

前端 未结 5 1654
南笙
南笙 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:26

    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
    

提交回复
热议问题