1
7

More than 5 years have passed since last update.

Python 辞書の使い方まとめ

Last updated at Posted at 2018-05-10

基本

空の辞書作成

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}
1
7
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
7