今さらPython3 (16) - 辞書のつづき

長くなってしまったので、中途半端なところで中断してしまった辞書(dist)のつづき。

入門 Python 3

入門 Python 3

全消去してみる

>>> pythons
{'chapman': 'Graham', 'Gilliam': 'Terry', 'Idle': 'Eric', 'Palin': 'Michael', 'Cleese': 'John', 'Jones': 'Terry'}
>>> pythons.clear()
>>> pythons
{}

clear()で行けると。実際には試してないけど、pythons={}でもOKだね。

存在チェック

>>> pythons = {'Chapman': 'Graham', 'Cleese': 'John', 'Jones': 'Terry', 'Palin': 'Michael'}
>>> pythons
{'Chapman': 'Graham', 'Jones': 'Terry', 'Palin': 'Michael', 'Cleese': 'John'}
>>> 'Chapman' in pythons
True
>>> 'Gilliam' in pythons
False

存在チェックはinでOK。実際のプログラムを考えると、辞書データを取得するときに存在しないキーを指定してしまった場合にエラーハンドリングすることを考えると、まずinでチェックしてから値を拾う感じにした方がいいんだろうね。

>>> pythons['Marx']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Marx'
>>> a = 'Marx'
>>> if a in pythons:
...     print(pythons[a])
... else:
...     print('Who is it?')
... 
Who is it?

怒られて中断するよりは、この方が良いかと。

>>> 'Marx' in pythons
False
>>> pythons.get('Cleese')
'John'
>>> pythons.get('Marx', 'Not a Python')
'Not a Python'
>>> pythons.get('Marx')
>>> 

あ、ちゃんと本にも書いてあったのね。get()を使った方が簡単だった。

キー、値の書きだし

>>> signals = {'green': 'go', 'yellow':'go faster', 'red': 'smile for the camera'}
>>> signals.keys()
dict_keys(['yellow', 'green', 'red'])
>>> list(signals.keys())
['yellow', 'green', 'red']

リストにする場合は、list()で囲って下さいとな。件数が多い場合時とかを考えると妥当な判断なんだろうか(棒)。

>>> list(signals.values())
['go faster', 'go', 'smile for the camera']
>>> list(signals.items())
[('yellow', 'go faster'), ('green', 'go'), ('red', 'smile for the camera')]

辞書の値だけを取り出すときはvalues()、キーと値をタプル形式で取り出す場合はitems()が使えるのね。となれば、こんな使い方も出来そう。

>>> for elem in signals.items():
...    key, value = elem
...    print(key, value)
... 
yellow go faster
green go
red smile for the camera
blue normal in Japan

イコールとコピーの話

これはリストの時と同じだね。

>>> signals
{'yellow': 'go faster', 'green': 'go', 'red': 'smile for the camera'}
>>> save_signals = signals
>>> signals['blue'] = 'confuse everyone'
>>> save_signals
{'yellow': 'go faster', 'green': 'go', 'red': 'smile for the camera', 'blue': 'confuse everyone'}
>>> 
>>> original_signals = signals.copy()
>>> signals['blue'] = 'normal in Japan'
>>> signals
{'yellow': 'go faster', 'green': 'go', 'red': 'smile for the camera', 'blue': 'normal in Japan'}
>>> original_signals
{'yellow': 'go faster', 'green': 'go', 'red': 'smile for the camera', 'blue': 'confuse everyone'}
>>> 

イコール(=)だと参照なので、片方を変更するともう片方も反映されるから、copy()を使ってくださいですね。

(つづく)