9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

python3.7でdictが格納順を保持するようになったが、pprint出力は自動でソートされる

Posted at

pythonのアップデートのきっかけになったので記念に投稿。
現在進行形でアップデートが進んでる言語なんですね。

ちなみに、動作確認は Python3.7.3 -> Python3.8.5 です。

python3.7以上はdictが格納順を保持する

めっちゃ便利!
しかし、pprintで出力をする場合、pprint出力前にソートをする 仕様のせいでいまいち恩恵が薄い。

test1.py
from pprint import pprint

d = {1: 10, 9: 90, 3: 30, 7: 70, 5: 50}
print(d)
pprint(d)
out1
{1: 10, 9: 90, 3: 30, 7: 70, 5: 50}
{1: 10, 3: 30, 5: 50, 7: 70, 9: 90}

1個ずつ代入した場合も同じ。

test2.py
from pprint import pprint

d2 = {}
d2[0] = 0
d2[8] = 80
d2[2] = 20
d2[6] = 60
d2[4] = 40
print(d2)
pprint(d2)
out2
{0: 0, 8: 80, 2: 20, 6: 60, 4: 40}
{0: 0, 2: 20, 4: 40, 6: 60, 8: 80}

python3.8以上でpprintsort_dicts=False指定ができる

python3.8から、pprintsort_dictsオプションが追加されたらしい。
デフォルトはsort_dicts=Trueになっているので、順序を保持したいならFalse指定が必要。

test3.py
from pprint import pprint

d = {1: 10, 9: 90, 3: 30, 7: 70, 5: 50}
print(d)
pprint(d, sort_dicts=False)
out3
{1: 10, 9: 90, 3: 30, 7: 70, 5: 50}
{1: 10, 9: 90, 3: 30, 7: 70, 5: 50}
9
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?