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