Pythonでdict型のキーとバリューを取得して、バリューの値でソートしたい時があります。
Python2とPython3ではその際に違った処理をしなければなりません。
まずはPython2
Python 2.7.9 (default, Jun 8 2015, 23:36:11)
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> d = {'a':5, 'b':2, 'c':9}
>>> key = d.keys() #辞書のキーをリストで取得
>>> key
['a', 'c', 'b']
>>> count = d.values() #辞書の値をリストで取得
>>> count
[5, 9, 2]
>>> key = np.array(key)
>>> count = np.array(count)
>>> key = key[count.argsort()]
>>> count.sort()
>>> count
array([2, 5, 9])
>>> key
array(['b', 'a', 'c'],
dtype='|S1')
次はPython3
Python 3.4.3 (default, Mar 5 2015, 21:43:46)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> d = {'a':5, 'b':2, 'c':9}
>>> key = d.keys() #辞書のキーをdict_keysオブジェクトで取得
>>> key
dict_keys(['c', 'a', 'b'])
>>> count = d.values() #辞書の値をdict_valuesオブジェクトで取得
>>> count
dict_values([9, 5, 2])
>>> key = list(key) #リストに変換
>>> key
['c', 'a', 'b']
>>> count = list(count) #リストに変換
>>> count
[9, 5, 2]
>>> key = np.array(key)
>>> count = np.array(count)
>>> key = key[count.argsort()]
>>> count.sort()
>>> count
array([2, 5, 9])
>>> key
array(['b', 'a', 'c'],
dtype='|S1')
Python3では、keysメソッドやvaluesメソッドでイテレータを返すことにより、
メモリの使用効率を落とさずにキーやバリューを取得できるそうです。


