メインコンテンツにスキップ
モジュール 3 · レッスン 3 / 4コース内の 11/36~12 min
モジュールのレッスン (3/4)

辞書

辞書 (dict) は キー → 値 マップです。キーを関連付けます。 (ほとんどの場合は文字列) 任意の型の値。それが基本です 現実世界のエンティティをモデル化するためのデータ構造。

辞書の作成

Python
vuoto = {}
utente = {"nome": "Ada", "anni": 36, "attivo": True}
# costruttore alternativo
utente = dict(nome="Ada", anni=36, attivo=True)

キーは ハッシュ可能 (不変) である必要があります: 文字列、数値、ハッシュ可能なタプル 要素。一方、値は、他の辞書であっても、何でも構いません。

アクセス、変更、削除

Python
utente["nome"]            # 'Ada'
utente["email"]           # KeyError!
utente.get("email")       # None       (default sicuro)
utente.get("email", "—")  # '—'        (default custom)
utente["citta"] = "Roma"  # aggiunge / aggiorna
del utente["attivo"]      # rimuove

dict を反復処理する

Python
for chiave in utente:               # itera sulle CHIAVI (default)
    print(chiave, utente[chiave])

for chiave in utente.keys():        # esplicito
    ...

for valore in utente.values():
    print(valore)

for chiave, valore in utente.items():    # idiom più comune
    print(f"{chiave} = {valore}")

反復順序は 挿入 の順序です (Python 3.7 以降で保証されています) 以降)。

鍵は存在するのでしょうか?

Python
"nome" in utente     # True
"email" in utente    # False     (NON usa il valore, usa la chiave!)

setdefault: 最初のアクセス時に初期化します

よくあるパターン: 「キーが存在しない場合は、デフォルトを入力します。キーが存在しない場合は、デフォルトを入力します。 場合は現在の値を返します。」

Python
gruppi = {}
for nome in ["Ada", "Linus", "Ada", "Grace", "Linus", "Ada"]:
    gruppi.setdefault(nome, []).append(1)
# {'Ada': [1, 1, 1], 'Linus': [1, 1], 'Grace': [1]}

カウントの特定のケース用の collections.Counter もあります ( stdlib モジュールで確認できます)。

辞書の反復処理

辞書は複数の方法で反復処理できます。

  • for k in d: キーのみをループします (デフォルトの動作)。
  • for k, v in d.items(): キーと値のペアを同時にループします (非常に便利)。
  • for v in d.values(): 値のみをループします。

試してみてください

運動#python.m3.l3.e1
試行回数: 0読み込み中…

`user = {'nome': 'Ada', 'anni': 36}` とすると、キー 'email' = 'ada@ex.com' を追加し、デフォルトの 'sconosciuto' で .get を使用してキー 'telefono' の値を `email_or_default` に割り当てます。 「email_or_default」を評価します。

エディターを読み込み中…
ヒントを表示

.get('telefono', 'sconosciuto') は KeyError を発生させません。

3 回の試行後に解決策が利用可能になります

復習演習

運動#python.m3.l3.e2
試行回数: 0読み込み中…

`prices = {'mela': 1.2, 'pera': 1.5, 'kiwi': 2.0}` とすると、すべての値の合計を計算し、それを `total` に代入します。 「合計」を評価します。

エディターを読み込み中…
ヒントを表示

sum(prices.values()) はすべての値を合計します。

3 回の試行後に解決策が利用可能になります

追加の課題

運動#python.m3.l3.e3
試行回数: 0読み込み中…

Given the dictionary `user = {'name': 'Alice'}`, use the `.get()` method to retrieve the value of the key `'role'`. If the key does not exist, make it return the default value `'guest'`. Store the result in `user_role` and evaluate it.

エディターを読み込み中…
ヒントを表示

get メソッドは、フォールバックとして 2 番目のパラメーター user.get('role', 'guest') を受け入れます。

3 回の試行後に解決策が利用可能になります