辞書

辞書 の Python

37個の演習

辞書について

Pythonの辞書(dict)は、ハッシュ可能な_キー_を_値_に対応付けるデータ構造で、他のプログラミング言語では、サイズを変更できるハッシュテーブル、ハッシュマップ、連想配列として知られています。辞書は、Pythonに組み込みの唯一のマッピング型です。

keysはハッシュ可能で、辞書の中で一意でなければなりません。キーの型には、number、str、tuple(_イミュータブル_な値)などを使用できます。list、dict、setのような_ミュータブル_なデータ構造を含めることはできません。Python 3.7以降、dictのキーの順序は、エントリを挿入した順序であることが保証されています。

valuesは、どんなデータ型や構造でもかまいません。値は_自由に_入れ子にできるので、リストのリスト、サブ辞書、その他のカスタムまたは複合的なデータ構造を含めることができます。

keyがわかっていれば、辞書は(平均して)一定時間でvalueを取り出せます(エントリの数に依存しません)。indexの位置を知らずにlistやarrayの中から値を探す場合と比べると、dictはメモリをかなり多く使いますが、取り出しは非常に高速です。

辞書は、項目の集まりが大きく、頻繁にアクセスして更新する必要がある場面で特に役立ちます。

辞書の作成

辞書は、さまざまな方法で作成できます。

  • fromkeys()クラスメソッドを使う。
  • 辞書内包表記を使う。
  • アンパック(**)で2つの辞書をマージする。
  • |(更新)演算子で辞書をマージする。
  • ループを使って、あらかじめ作成した空のdictにエントリを1つずつ追加する。

最もわかりやすいのは、辞書の_コンストラクター_と辞書の_リテラル_の2つです。

辞書のコンストラクター

dict()(dictクラスのコンストラクター)は、keyとvalueのペアの反復可能オブジェクトならどれでも使えます。また、一連の<name>=<value>_引数_を渡して呼び出すこともできます。

# Passing a list of key,value tuples.
>>> wombat = dict([('name', 'Wombat'),
...              ('speed', 23),
...              ('land_animal', True)])
{'name': 'Wombat', 'speed': 23, 'land_animal': True}


# Using key=value arguments.
>>> bear = dict(name="Black Bear",
...             speed=40,
...             land_animal=True)
{'name': 'Black Bear', 'speed': 40, 'land_animal': True}

dictのドキュメントには、コンストラクターの使い方のその他のバリエーションやオプションが説明されています。

辞書リテラル

辞書は、_辞書リテラル_として直接書くこともできます。key : valueのペアを波括弧({})で囲みます。{}で囲むエントリは、別々の行に書くこともできます。

>>> whale = {"name": "Blue Whale", 
             "speed": 35, 
             "land_animal": False}
{'name': 'Blue Whale', 'speed': 35, 'land_animal': False}

>>> wombat = {'name': 'Wombat',
              'speed': 23,
              'land_animal': True,
              'color': 'Brindle'}

>>> wombat
{'name': 'Wombat', 'speed': 23, 'land_animal': True, 'color': 'Brindle'}

入れ子の辞書

辞書は自由に入れ子にできます。

animals = {
    "Real" : {
        "Winged" : {
            "Sparrow" : {'name': 'sparrow','speed': 12, 'land_animal': True},
            "Kestrel" : {'name': 'kestrel', 'speed': 15, 'land_animal': True}
           },
        "Legged" : {
            "Wombat" : {'name': 'Wombat', 'speed': 23, 'land_animal': True},
            "Black Bear": {'name': 'Black Bear', 'speed': 40, 'land_animal': True},
            "Polecat" : {'name': 'Polecat', 'speed': 15, 'land_animal': True}
           },
        "Other" :  {
            "Whale" : {'name': 'Blue Whale', 'speed': 35, 'land_animal': False},
            "Orca" : {'name': 'Orca', 'speed': 45, 'land_animal': False},
            "Snake" : {'name': 'Python', 'speed': 25, 'land_animal': True}
            }
        },
        
    "Imaginary": {
        "Winged" : {
            "Dragon" : {'name': 'Fire Dragon','speed': 100, 'land_animal': True},
            "Phoenix" : {'name': 'Phoenix', 'speed': 1500, 'land_animal': True}
            },
        "Legged" : {
            "Sphinx" : {'name': 'Sphinx','speed': 10, 'land_animal': True},
            "Minotaur" : {'name': 'Minotaur', 'speed': 5, 'land_animal': True}
            },
        "Other" :  {}
        }
   }

dictの値にアクセスする

辞書のvalueには、角括弧([])に_key_を書いてアクセスします。辞書にキーが存在しない場合は、KeyErrorが送出されます。

>>> bear["speed"]
40

>>> bear["color"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'color'

get(<key>, <default value>)メソッドでエントリにアクセスすると、KeyErrorを避けられます。

>>> bear.get("color", 'not found')
'not found'

入れ子の辞書のエントリにアクセスする

入れ子の辞書のエントリにアクセスするには、角括弧をつなげて書きます。キーが存在しない場合は、通常どおりKeyErrorが送出されます。

# Using the animals nested dictionary.
>>> animals["Real"]["winged"]["Kestrel"]["speed"]
15

>>> animals["Imaginary"]["winged"]["Kestrel"]["speed"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Kestrel'

KeyErrorを避けるには.get()を使いますが、.get()の呼び出しは_チェーン_する必要があります。

# Using the animals nested dictionary.
# Note the use of parenthesis to enable placing the 
# .get() calls on separate lines.
>>> (animals.get("Imaginary", {})
            .get("Legged", {})
            .get("Sphinx", {})
            .get("Color", "I have no idea!"))
'I have no idea!'

辞書の値を変更・追加する

エントリのvalueは、その_key_に代入することで変更できます。

# Assigning the value "Grizzly Bear" to the name key.
>>> bear["name"] = "Grizzly Bear"
{'name': 'Grizzly Bear', 'speed': 40, 'land_animal': True}

>>> whale["speed"] = 25
{'name': 'Blue Whale', 'speed': 25, 'land_animal': False}

新しいkey:valueのペアも、同じように_追加_できます。

# Adding a new "color" key with a new "tawney" value.
>>> bear["color"] = 'tawney'
{'name': 'Grizzly Bear', 'speed': 40, 'land_animal': True, 'color': 'tawney'}

>>> whale["blowholes"] = 1
{'name': 'Blue Whale', 'speed': 25, 'land_animal': False, 'blowholes': 1}

辞書のエントリを削除する(popとdel)

<dict>.pop(<key>)メソッドを使うと、辞書のエントリを削除できます。<dict>.pop()は(key、value)のペアを削除し、valueを返します。<dict>.get()と同様に、<dict>.pop(<key>)は2番目の引数(<dict>.pop(<key>, <default value>))を受け取り、keyが見つからない場合にその値を返します。これによりKeyErrorが発生するのを防げます。

# Using .pop() removes both the key and value, returning the value.
>>> bear.pop("name")
'Grizzly Bear'


# The "name" key is now removed from the dictionary.
# Attempting .pop() a second time will throw a KeyError.
>>> bear.pop("name")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'name'


# Using a default argument with .pop() will 
# prevent a KeyError from a missing key.
>>> bear.pop("name", "Unknown")
'Unknown'

del文を使って、1つ以上のエントリを削除することもできます。削除しようとしたエントリが辞書に見つからない場合は、KeyErrorが発生します。

>>> wombat = {'name': 'Wombat',
              'speed': 23,
              'land_animal': True,
              'color': 'Brindle',
              'talent': 'Singing',
              'size': 'small'}

# Remove a single entry from the dictionary.
>>> del wombat["color"]
>>> wombat
{'name': 'Wombat', 'speed': 23, 'land_animal': True, 'talent': 'Singing', 'size': 'small'}


# Remove multiple entries from the dictionary.
>>> del wombat["talent"], wombat["size"]
>>> wombat
{'name': 'Wombat', 'speed': 23, 'land_animal': True}


# Attempting a deletion of a non-existent key raises a KeyError
>>> del wombat["number_of_legs"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'number_of_legs'

辞書をループする/繰り返し処理する

for item in dictやwhile itemで辞書をループすると、デフォルトでは_keys_が繰り返されます。同じループの中で_角括弧_を使えば_values_にアクセスできます。

>>> for key in bear:
...     print((key, bear[key])) # <--This prints a tuple of (key, value).
('name', 'Black Bear')
('speed', 40)
('land_animal', True)

(key, value)のタプルを返す.items()メソッドを使うこともできます。

# dict.items() forms (key, value tuples) that can be 
# unpacked and iterated over.
>>> for key, value in whale.items():
...     print(key, ":", value)
name : Blue Whale
speed : 25
land_animal : False
blowholes : 1

同じように、.keys()はkeysを、.values()はvaluesを返します。

Pythonの辞書について詳しく知りたい場合は、公式ドキュメントから始めるのがおすすめです。ほかには、W3-Schoolsのチュートリアルも参考になります。

辞書の機能を拡張する:collectionsモジュール

collectionsモジュールは、Python標準のコレクション型のデータ型(dict、set、list、tuple)に特化した機能を追加します。特に便利な辞書ベースのクラスを3つ紹介します。

  • Counterは、項目を自動で数え、項目をキー、その個数を値とするdictとして返します。
  • OrderedDictには、辞書のエントリの順序を並べ替えるための専用メソッドがあります。
  • defaultdictは、辞書のエントリを取り出したり代入したりするときにkeyが見つからない場合、ファクトリーメソッドを使ってデフォルト値を設定します。
GitHubで編集 リンクは新しいウィンドウまたはタブで開きます

辞書を学習する

練習はロックされています

辞書を練習するには、あと4個の演習のロックを解除してください