どうも、ちょげ(@chogetarou)です。
Python3.7以降で辞書(Dictionary)をランダムにソートする方法を紹介します。
方法

Python3.7以降で辞書(Dictionary)をランダムにソートするには、randomとListを使います。
まず、randomをインポートします。
import random
次に、辞書のitems()をListに変換します。
random.shuffle()を呼び出し、random.shuffle()の引数にitems()を変換したlistを指定します。
そして、items()を変換したlistを辞書に変換します。
myList = list(myDict.items())
random.shuffle(myList)
result = dict(myList)
上記の処理で、items()を呼び出した辞書をランダムにソートした辞書が生成されます。
使用例
import random
numbers = { "one":1, "two":2, "three":3, "four":4, "five":5 }
myList = list(numbers.items())
random.shuffle(myList)
result = dict(myList)
print(numbers)
print(result)
出力:
{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
{'three': 3, 'one': 1, 'five': 5, 'four': 4, 'two': 2}
コメント