Python の Defaultdict

辞書 Python の は、マップのようにデータ値を格納するために使用されるデータ値の順序付けされていないコレクションです。要素として単一の値のみを保持する他のデータ型とは異なり、ディクショナリはキーと値のペアを保持します。 Dictionary では、キーは一意かつ不変である必要があります。これは、Python タプルはキーになり得るが、Python リストはキーになり得ないことを意味します。辞書は、一連の要素を中かっこ {} 内に「カンマ」で区切って配置することで作成できます。

例:

Python3




# Python program to demonstrate> # dictionary> > > Dict> => {> 1> :> 'Geeks'> ,> 2> :> 'For'> ,> 3> :> 'Geeks'> }> print> (> 'Dictionary:'> )> print> (> Dict> )> print> (> Dict> [> 1> ])> > # Uncommenting this print(Dict[4])> # will raise a KeyError as the> # 4 is not present in the dictionary>

出力:

Dictionary: {1: 'Geeks', 2: 'For', 3: 'Geeks'} Geeks 
Traceback (most recent call last): File '/home/1ca83108cc81344dc7137900693ced08.py', line 11, in print(Dict[4]) KeyError: 4 

KeyError が発生すると、問題が発生することがあります。これを克服するために、Python では、別の辞書のようなコンテナーを導入します。 デフォルトディクショナリ これはコレクションモジュール内に存在します。
注記: 詳細については、以下を参照してください。 Python辞書

デフォルト辞書

デフォルトディクショナリ のようなコンテナです 辞書 モジュール内に存在する コレクション 。 Defaultdict は、辞書のようなオブジェクトを返す辞書クラスのサブクラスです。ディクショナリとdefaultdictの両方の機能は、defaultdictがKeyErrorを発生させないことを除いて、ほぼ同じです。存在しないキーのデフォルト値を提供します。

構文: defaultdict(デフォルト_ファクトリー)
パラメーター:

    default_factory: 定義された辞書のデフォルト値を返す関数。この引数が存在しない場合、辞書は KeyError を生成します。

例:

Python3




# Python program to demonstrate> # defaultdict> > > from> collections> import> defaultdict> > > # Function to return a default> # values for keys that is not> # present> def> def_value():> > return> 'Not Present'> > # Defining the dict> d> => defaultdict(def_value)> d[> 'a'> ]> => 1> d[> 'b'> ]> => 2> > print> (d[> 'a'> ])> print> (d[> 'b'> ])> print> (d[> 'c'> ])>

出力:

1 2 Not Present 

defaultdict の内部動作

Defaultdict は、標準の辞書操作に加えて、1 つの書き込み可能なインスタンス変数と 1 つのメソッドを追加します。インスタンス変数はdefault_factoryパラメータであり、提供されるメソッドは__missing__です。

    Default_factory: 定義された辞書のデフォルト値を返す関数です。この引数が存在しない場合、辞書は KeyError を生成します。
    例:

Python3




# Python program to demonstrate> # default_factory argument of> # defaultdict> > > from> collections> import> defaultdict> > > # Defining the dict and passing> # lambda as default_factory argument> d> => defaultdict(> lambda> :> 'Not Present'> )> d[> 'a'> ]> => 1> d[> 'b'> ]> => 2> > print> (d[> 'a'> ])> print> (d[> 'b'> ])> print> (d[> 'c'> ])>

出力:

1 2 Not Present 
    __missing__(): この関数は、辞書のデフォルト値を提供するために使用されます。この関数は引数としてdefault_factoryを受け取り、この引数がNoneの場合はKeyErrorが発生し、それ以外の場合は指定されたキーのデフォルト値が提供されます。このメソッドは基本的に、要求されたキーが見つからない場合に、dict クラスの __getitem__() メソッドによって呼び出されます。 __getitem__() は、__missing__() によって返された値を生成または返します。方法。
    例:

Python3




# Python program to demonstrate> # defaultdict> > > from> collections> import> defaultdict> > > # Defining the dict> d> => defaultdict(> lambda> :> 'Not Present'> )> d[> 'a'> ]> => 1> d[> 'b'> ]> => 2> > # Provides the default value> # for the key> print> (d.__missing__(> 'a'> ))> print> (d.__missing__(> 'd'> ))>

出力:

Not Present Not Present 

リストをdefault_factoryとして使用する

list クラスがdefault_factory引数として渡されると、listの値を使用してdefaultdictが作成されます。
例:

Python3




# Python program to demonstrate> # defaultdict> > > from> collections> import> defaultdict> > > # Defining a dict> d> => defaultdict(> list> )> > for> i> in> range> (> 5> ):> > d[i].append(i)> > print> (> 'Dictionary with values as list:'> )> print> (d)>

出力:

Dictionary with values as list: defaultdict(, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}) 

int をdefault_factory として使用する

int クラスがdefault_factory引数として渡されると、デフォルト値がゼロのdefaultdictが作成されます。
例:

Python3




# Python program to demonstrate> # defaultdict> > > from> collections> import> defaultdict> > > # Defining the dict> d> => defaultdict(> int> )> > L> => [> 1> ,> 2> ,> 3> ,> 4> ,> 2> ,> 4> ,> 1> ,> 2> ]> > # Iterate through the list> # for keeping the count> for> i> in> L:> > > # The default value is 0> > # so there is no need to> > # enter the key first> > d[i]> +> => 1> > print> (d)>

出力:

defaultdict(, {1: 2, 2: 3, 3: 1, 4: 2})