LoginSignup
8
9

More than 3 years have passed since last update.

Python 辞書型(dictionary) まとめ

Last updated at Posted at 2019-08-11

はじめに

辞書型についてうまくまとめられた記事が見当たらなかったので自分用にまとめてみました。
AtcoderをPython使ってやってます。

初期化について

空の辞書型
>>> d = {}
>>> d
{}

{string: int, string: string, int: int} など色々入れれる

値を入れて初期化
>>> d = {'x': 1, 'y': 'yyyy', 1: 1000, 'list': [10, 20]}
>>> d
{'x': 1, 'y': 'yyyy', 1: 1000}
dictメソッドを使って
>>> d = dict(a=10, b=20)
>>> d
{'a': 10, 'b': 20}

値の追加について

代入
>>> d={}
>>> d['x'] = 10
>>> d
{'x': 10}
setdefaultメソッド
>>> d = {}
>>> d.setdefault('x', 1000)
1000
>>> d
{'x': 1000}

>>> d.setdefault('x', 2000)
1000
>>> d
{'x': 1000}

便利なメソッド

キー、バリューの取り出し

keys()
>>> d = {'x': 10, 'y': 20}
>>> d.keys()
dict_keys(['x', 'y'])
values()
>>> d = {'x': 10, 'y': 20}
>>> d.values()
dict_values([10, 20])

要素をオーバーライド

update()
>>> d = {'x': 10, 'y': 20}
>>> d2 = {'x': 30, 'i': 100}
>>> d
{'x': 10, 'y': 20}
>>> d2
{'x': 30, 'i': 100}

>>> d.update(d2)
>>> d
{'x': 30, 'y': 20, 'i': 100}

要素の取得

get()
>>> d = {'x': 10, 'y': 20}
>>> d['x']
10
>>> d.get('x')
10

# keyにないものを取り出そうとするとエラーになる
>>> d['z']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'z'

# getメソッドを使うとNoneが返ってくる
>>> r = d.get('z')
>>> type(r)
<class 'NoneType'>

要素を取り出しつつ削除

pop()
>>> d = {'x': 10, 'y': 20}
>>> d.pop('x')
10
>>> d
{'y': 20}
del
>>> d = {'x': 10, 'y': 20, 'z': 30}
>>> del d['x']
>>> d
{'y': 20, 'z': 30}
>>> del d
>>> d
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
辞書を空にする
>>> d = {'x': 10, 'y': 20}
>>> d
{'x': 10, 'y': 20}
>>> d.clear()
>>> d
{}

キーがあるか判定

in
>>> d = {'x': 10, 'y': 20}
>>> d
{'x': 10, 'y': 20}
>>> 'x' in d
True
>>> 'z' in d
False

コピー

変数はオブジェクトへの参照を保持するため、変数代入ではコピーができない
>>> d = {'x': 10}
>>> d2 = d
>>> d2['x'] = 20
>>> d
{'x': 20}
>>> d2
{'x': 20}
コピーメソッドを使う
>>> d = {'x': 10}
>>> d2 = d.copy()
>>> d2['x'] = 20
>>> d
{'x': 10}
>>> d2
{'x': 20}

ソートメソッド

sorted
>>> d = {'z': 10, 'y': 20, 'x': 30}
>>> sorted(d.items())
[('x', 30), ('y', 20), ('z', 10)]
>>> d
{'z': 10, 'y': 20, 'x': 30}
>>> d = sorted(d.items())
>>> d
[('x', 30), ('y', 20), ('z', 10)]
8
9
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
8
9