Python: dictionaryデータ構造でキーバリュー
初めてdictionaryデータ構造を使います。
キー:バリュー形式で、キーを手がかりにして値を探す場合には速度面でもっとも有利な構造と「初めてのPython」には書いてあります。
遭遇したユースケース
あるデータに対して、それぞれ別の処理を施した結果が
いくつかのファイルに(処理毎に)作られています。
各ファイルは
サンプル名1 処理結果1
サンプル名2 処理結果2
.......
というふうに並んでいます。ただし、サンプルの並び方はファイルによってまちまちです。で、やりたいのは、各サンプル毎に異なる処理結果を集約したい、という状況です。
dictionaryの使い方
データを準備。
%cat op1.txt
giants 1
tigers 2
carp 3
dragons 4
baystars 5
swallows 6
%cat op2.txt
giants 1
dragons 2
swallows 3
carp 4
tigers 5
baystars 6
%cat op3.txt
dragons 1
swallows 2
giants 3
tigers 4
carp 5
baystars 6
OK.では各ファイルごとにdictionaryデータ構造をつくる。
>>> Dic1 = {}
>>> Dic2 = {}
>>> Dic3 = {}
>>> with open('op1.txt', 'r') as fin:
... for line in fin:
... splitted = line.rstrip().split()
... key = splitted[0]
... val = splitted[1]
... Dic1[key] = val
...
>>> print Dic1
{'giants': '1', 'tigers': '2', 'swallows': '6', 'dragons': '4', 'baystars': '5', 'carp': '3'}
>>> (中略)
>>> print Dic2
{'giants': '1', 'carp': '4', 'swallows': '3', 'dragons': '2', 'baystars': '6', 'tigers': '5'}
>>> print Dic3
{'giants': '3', 'tigers': '4', 'swallows': '2', 'dragons': '1', 'baystars': '6', 'carp': '5'}
これで、キーからすぐに値を呼び出せる。じゃあまとめましょう。
>>> with open('central_result11-13.txt','w') as fout:
... fout.write('team, 2013, 2012, 2011\n')
... for key in sorted(Dic1):
... fout.write(key + ', ' + Dic1[key] + ', ' + Dic2[key] + ', ' + Dic3[key] + '\n')
...
$ cat central_result11-13.txt team, 2013, 2012, 2011
baystars, 5, 6, 6
carp, 3, 4, 5
dragons, 4, 2, 1
giants, 1, 1, 3
swallows, 6, 3, 2
tigers, 2, 5, 4