リスト型の場合、要素名は0,1,2,・・・の数字でしたが、ディクショナリ型の場合、要素名は指定の文字列になります。
ディクショナリ型の初期化は変数名 = [要素名:値,要素名:値・・・]になります。
・値の初期化
スクリプト
実行結果
ディクショナリ型の値の初期化と表示を行なっています。
ディクショナリ型は{ }で初期化を行ないます。
・値の取得
スクリプト
実行結果
ディクショナリ型の初期化は変数名 = [要素名:値,要素名:値・・・]になります。
・値の初期化
スクリプト
test_dict_1 = {'year':'2014','month':'11','day':'25'}
print (test_dict_1)
print ('=================================')
for i in test_dict_1:
print (i)
print (test_dict_1[i])
print ('=================================')
実行結果
{'month': '11', 'day': '25', 'year': '2014'}
=================================
month
11
=================================
day
25
=================================
year
2014
================================= ディクショナリ型の値の初期化と表示を行なっています。
ディクショナリ型は{ }で初期化を行ないます。
・値の取得
スクリプト
test_dict_1 = {'year':'2014','month':'11','day':'25'}
print (test_dict_1)
print ('=================================')
print (test_dict_1['year'])
print ('=================================')
print (test_dict_1.get('year'))
print (test_dict_1.get('years'))
print ('=================================')
print (test_dict_1.get('year','not found'))
print (test_dict_1.get('years','not found')) 実行結果
{'day': '25', 'month': '11', 'year': '2014'}
=================================
2014
=================================
2014
None
=================================
2014
not found
値の取得はディクショナリ名['要素名']で行ないます。
ここで存在しない要素名を指定した場合はエラーが発生します。
また、ディクショナリ名.get('要素名')でも値を取得することが出来ますが、こちらの場合、要素名が存在しない場合、エラーではなく「None」を返します。
なお、要素名が存在しない場合の表示はget関数の第二引数で指定することが出来ます。
・値の追加
スクリプト
実行結果
値を空にしてディクショナリ型の初期化を行なった後、「ディクショナリ名['要素名']=値」で値を追加しています。
・値の削除
スクリプト
print (test_dict_1)
実行結果
ディクショナリ型の削除を行なう場合、del関数を利用します。
値の取得はディクショナリ名['要素名']で行ないます。
ここで存在しない要素名を指定した場合はエラーが発生します。
また、ディクショナリ名.get('要素名')でも値を取得することが出来ますが、こちらの場合、要素名が存在しない場合、エラーではなく「None」を返します。
なお、要素名が存在しない場合の表示はget関数の第二引数で指定することが出来ます。
・値の追加
スクリプト
test_dict_1 ={}
print (test_dict_1)
print ("============================")
test_dict_1['year'] = '2014'
test_dict_1['month'] = '11'
test_dict_1['day'] = '26'
print (test_dict_1)
実行結果
{}
============================
{'month': '11', 'year': '2014', 'day': '26'}
値を空にしてディクショナリ型の初期化を行なった後、「ディクショナリ名['要素名']=値」で値を追加しています。
・値の削除
スクリプト
test_dict_1 ={'year':'2014','month':'11','day':'26'}
print (test_dict_1)
print ("============================")
del test_dict_1['year']
実行結果
{'day': '26', 'year': '2014', 'month': '11'}
============================
{'day': '26', 'month': '11'} ディクショナリ型の削除を行なう場合、del関数を利用します。

コメント