LoginSignup
2
1

More than 5 years have passed since last update.

Pythonのdictにおいて属性でのアクセスと挿入順の保持を実現する方法

Last updated at Posted at 2017-02-19

Pythonのdictにおいて、以下を実現する方法についてまとめます。

  • 属性でのアクセス
d.a = 1
  • 挿入順の保持

実現するオブジェクト

属性でのアクセスのみ

attrdict.AttrDictで実現できます。

インストール方法

$ pip install attrdict

属性でのアクセスと挿入順の保持

collections.OrderedDictで実現できます。

初期化の際の注意

以下のように記述すると順番が保持されなくなります。

良くない例
# coding=utf-8
import collections

# メイン処理
if __name__ == '__main__':
    # 引数として要素を与えて初期化を行うと順番が保持されない
    d = collections.OrderedDict(a=1, b=2, c=3, d=4)

    # dのkeyとvalueを順番に表示
    for k, v in d.items():
        print('{} : {}'.format(k, v))

そのため、初期化を行いたい場合には以下のようにタプルにする必要があります。

良い例
# coding=utf-8
import collections

# メイン処理
if __name__ == '__main__':
    # タプルとして要素を与えて初期化を行うと順番が保持される
    d = collections.OrderedDict((('a', 1), ('b', 2), ('c', 3), ('d', 4)))

    # dのkeyとvalueを順番に表示
    for k, v in d.items():
        print('{} : {}'.format(k, v))

元ネタ

参考文献

2
1
1

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