辞書の使い方

Python のデータ型

Jason Myers

Instructor

辞書の作成とループ処理

  • キーと値のペアでデータを保持する
  • ネスト可能(辞書のキーの値として別の辞書を使用できる)
  • イテラブル
  • dict() または {} で作成
art_galleries = {}

for name, zip_code in galleries:
    art_galleries[name] = zip_code
Python のデータ型

ループ内での出力

for name in sorted(art_galleries)[-5:]:
    print(name)
Zwirner David Gallery
Zwirner & Wirth
Zito Studio Gallery
Zetterquist Galleries
Zarre Andre Gallery
Python のデータ型

キーによる安全な検索

art_galleries['Louvre']
|--------------------------------------------------------------------
KeyError                            Traceback (most recent call last)
<ipython-input-1-4f51c265f287> in <module>()
--> 1 art_galleries['Louvre']

KeyError: 'Louvre'
  • 辞書から値を取得するにはキーをインデックスとして使用する
  • 存在しないキーを指定すると KeyError が発生し、プログラムが停止する
Python のデータ型

キーによる安全な検索(続き)

  • .get() メソッドを使うと、エラー処理なしに安全にキーへアクセスできる
  • キーが存在しない場合、.get() はデフォルトで None を返すか、戻り値を指定できる
art_galleries.get('Louvre', 'Not Found')
'Not Found'
art_galleries.get('Zarre Andre Gallery')
'10011'
Python のデータ型

練習しましょう!

Python のデータ型

Preparing Video For Download...