基本
空の辞書作成
dict = {}
辞書への値追加
dict["dog"]="pochi"
辞書のキー取得
dict.keys()
>>> dict["dog"]="pochi"
>>> dict["cat"]="tama"
>>> dict.keys()
dict_keys(['dog', 'cat'])
辞書の値の取得
dict.values()
>>> dict.values()
dict_values(['pochi', 'tama'])
ちょっと応用
python 辞書 keyを数字で並び替え
sorted(dict.keys(), key=int)
>>> dict.keys()
dict_keys([1, 2, 3, 4, 100, 50])
>>> sorted(dict.keys(),key=int)
[1, 2, 3, 4, 50, 100]
リストの分類分け(カウント)
>>> dict ={}
>>> list = ["dog","dog","cat","dog"]
>>> for i in list:
... if i in dict.keys():
... dict[i] += 1
... else:
... dict[i] = 0
... dict[i] += 1
...
>>> dict
{'dog': 3, 'cat': 1}