順序付きディクショナリ (2.6以前)
Python標準のディクショナリは追加した順番は保持してくれません。 keyを指定して取り出す場合は問題ありませんが、追加した順序通りに取得したい場合は外部ライブラリの「odict.py」を使用します※。
※Python 2.7以降で順書付きディクショナリを使用したい場合は、標準ライブラリである OrderedDict を使用してください。
※順書付きディクショナリの標準ライブラリ化(OrderedDict)にともない、odict.py は現在配布されていないようです。Python 2.6以前でOrderedDictを使用したい場合は PyPI(Python Package Index)から入手することができます。
まずは標準のディクショナリの出力を見てみましょう。 ※実行環境によっては出力される順番が変わる可能性があります。
# -*- 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
「odict.py」は下記リンクよりダウンロードしてください。
※現在下記リンクにodict.pyはありません、2.6以前で順序付きディクショナリを使用する場合は PyPIから入手してください。
http://dev.pocoo.org/hg/sandbox/raw-file/tip/odict.py
ダウンロードしたファイルを「"Pythonoをインストールしたディレクトリ"\Lib\site-packages」へ置き、先程のコードを修正します。
# -*- coding: utf-8 -*-
import odict
test_dict = odict.odict()
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
実行結果の通り追加した順番で出力されます。順序付きディクショナリが無いバージョンのPythonを使用している際に利用すると良いでしょう。
Python 2.6以前でOrderedDictを使用する場合はPyPIから入手することができます。 下記コマンドを入力し「ordereddict」モジュールをインストールします。 ※これはpipがインストールされていることを前提としています。インストールしていない場合は pipの使い方とインストール を参照してください。
pip install ordereddict
インストール後は次のように使用することができます。標準ライブラリの方のOrderedDictとはモジュール名が異なるので注意しましょう。
# -*- coding: utf-8 -*-
import ordereddict
test_dict = ordereddict.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
次は結構な需要があるかも?? PDFを生成してみましょう!
