How to iterate through dict in random order in Python?

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

    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)
    

提交回复
热议问题