1
2

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 5 years have passed since last update.

Python基礎 dictのソート順

Last updated at Posted at 2015-06-16

おもむろにDict をprint

$ python 
>>> a = {}
>>> a["b"] = 1
>>> a["d"] = 2
>>> a["c"] = 3
>>> a["a"] = 4
>>> print a
{'a': 4, 'c': 3, 'b': 1, 'd': 2}

→ばらばらですね。。

list はどうだろう

$ python 
>>> a = []
>>> a.append(1)
>>> a.append(2)
>>> a.append(3)
>>> a.append(4)
>>> a.append(9)
>>> a.append(8)
>>> print a
[1, 2, 3, 4, 9, 8]

→これはOKみたい。

Dictを登録した順で使いたんだけど。。

OrderedDict というものが有るらしい!

$ python 
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d["b"] = 1
>>> d["d"] = 2
>>> d["c"] = 3
>>> d["a"] = 4
>>> print d
OrderedDict([('b', 1), ('d', 2), ('c', 3), ('a', 4)])

→できてますね。

まとめ

pythonだとあまり意識しないところ?ですが、こんな癖がありました。という共有まで。

参考)
http://docs.python.jp/2/tutorial/datastructures.html#tut-dictionaries
>辞書は順序付けのされていない キー(key): 値(value) のペアの集合であり...

1
2
2

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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?