Python 辞書型の基本
目的
Python3で便利な辞書型の基本的なコードを書いて覚える。
辞書型データの作成
>>> test_dict= {'key0':'value0','key1':'value1','key2':'value2'}
>>> test_dict
{'key0': 'value0', 'key1': 'value1'}
要素の取り出し
>>> test_dict['key0']
'value0'
>>> test_dict.get('key0')
'value0'
>>>test_dict.get('key3','No value3')
'No value3'
全キーの取得
>>> test_dict.keys()
dict_keys(['key0', 'key1', 'key2'])
>>>list(test_dict.keys())
['key0', 'key1', 'key2']
全値の取得
>>> test_dict.values()
dict_values(['value0', 'value1', 'value2'])
>>> list(test_dict.values())
['value0', 'value1', 'value2']
全キーおよび値の取得
>>> test_dict.items()
dict_items([('key0', 'value0'), ('key1', 'value1'), ('key2', 'value2')])
>>> list(test_dict.items())
[('key0', 'value0'), ('key1', 'value1'), ('key2', 'value2')]
リスト型から辞書型への変換
>>> test_list = [['key0','value0'],['key1','value1'],['key2','value2']]
>>> dict(test_list)
{'key0': 'value0', 'key1': 'value1', 'key2': 'value2'}
キーの有無確認
>>> 'key3' in test_dict
False
>>> 'key2' in test_dict
True
要素の追加
>>> test_dict['key3'] = 'value3'
>>> test_dict
{'key0': 'value0', 'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
要素の削除
>>> del test_dict['key3']
>>> test_dict
{'key0': 'value0', 'key1': 'value1', 'key2': 'value2'}
辞書の結合
>>> test_dict2= {'key3':'value3','key4':'value4'}
>>> test_dict.update(test_dict2)
>>> test_dict
{'key0': 'value0',
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4'}
要素の全削除
>>> test_dict.clear()
>>> test_dict
{}