順序付きディクショナリ (2.7以降)
Python標準のディクショナリは追加した順番は保持してくれません。 keyを指定して取り出す場合は問題ありませんが、追加した順序通りに取得したい場合は「OrderedDict」を使用します。
※Python 2.6 以前で追加した順番を保持するディクショナリを使用したい場合は PyPIから入手 してください。
まずは標準のディクショナリの出力を見てみましょう。 ※実行環境によっては出力される順番が変わる可能性があります。
# -*- coding: utf-8 -*-
test_dict = {}
test_dict['word'] = 'doc'
test_dict['excel'] = 'xls'
test_dict['access'] = 'mdb'
test_dict['powerpoint'] = 'ppt'
test_dict['notepad'] = 'txt'
test_dict['python'] = 'py'
for key in test_dict:
print key
--実行結果--
word python notepad excel access powerpoint
追加した順序を記憶しておく「OrderedDict」を試してみましょう。
# -*- coding: utf-8 -*-
import collections
test_dict = collections.OrderedDict()
test_dict['word'] = 'doc'
test_dict['excel'] = 'xls'
test_dict['access'] = 'mdb'
test_dict['powerpoint'] = 'ppt'
test_dict['notepad'] = 'txt'
test_dict['python'] = 'py'
for key in test_dict:
print key
--実行結果--
word excel access powerpoint notepad python
実行結果の通り追加した順番で出力されます。
セットの真価はここにある!
▶応用編:セットの比較・作成・更新
