0
0

More than 3 years have passed since last update.

【Udemy Python3入門+応用】 25. 辞書型のメソッド

Posted at

※この記事はUdemyの
現役シリコンバレーエンジニアが教えるPython3入門+応用+アメリカのシリコンバレー流コードスタイル
の講座を受講した上での、自分用の授業ノートです。
講師の酒井潤さんから許可をいただいた上で公開しています。

■辞書型のメソッド

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

.keysで辞書内のkeyを、
.valuesで辞書内のvalueを表示させることができる。

.update
>>> d = {'x': 10, 'y': 20}
>>> d2 = {'x':1000, 'z': 500}
>>> d.update(d2)
>>> d
{'x': 1000, 'y': 20, 'z': 500}

xの値は更新され、zの値は追加された。

.get.pop
>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> d['x']
1000

もちろん、[]でkeyを指定するとそのkeyのvalueが返る。

>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> d.get('x')
1000
>>> d
{'x': 1000, 'y': 20, 'z': 500}

.getでkeyを指定すると、valueを取り出せる。
このときdの中身は変わっていない。

>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> d.pop('x')
1000
>>> d
{'y': 20, 'z': 500}

.popを使ってもvalueを取り出すことができるが、
.getとは異なり、取り出したデータはdからなくなる。

◆存在しないkeyを指定した場合
>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> d['a']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'a'
>>> d.get('a')
>>> n = d.get('a')
>>> type(n)
<class 'NoneType'>

d['a']とするとエラーとなってしまうが、
d.get('a')とした場合、NoneTypeとなる。

.clear
>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> d.clear()
>>> d
{}

.clear()を使うと、辞書内のデータがすべて消去される。

del
>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> del d['x']
>>> d
{'y': 20, 'z': 500}

もちろんdelも使用可能。

in
>>> d = {'x': 1000, 'y': 20, 'z': 500}
>>> 'x' in d
True
>>> 'a' in d
False

'x' in d
"Does 'x' exist in d?"
となる。

0
0
0

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
0
0