Python dict() 関数
辞書は変更可能なデータ構造です。つまり、辞書内のデータは変更できます。辞書はインデックス付きのデータ構造です。つまり、辞書の内容にはインデックスを使用してアクセスできます。ここでの辞書では、キーがインデックスとして使用されます。ここで、 dict()> 関数は、新しい辞書を作成するか、他の反復可能なオブジェクトを辞書に変換するために使用されます。この記事では、Python dict() 関数について詳しく学習します。
Python dict() の構文
dict(**kwarg)
dict(反復可能、**kwarg)
dict(マッピング、**kwarg)パラメーター:
クワーグス : キーワード引数.terableです。
反復可能な : キーワード引数を含む反復可能
マッピング :別の辞書です。
Python の dict() 関数
dict()> 関数は、新しい辞書を作成するか、他の反復可能なオブジェクトを辞書に変換するために使用されます。 Python の辞書はキーと値のペアのコレクションであり、 dict()> 関数を使用すると、さまざまな方法で作成できます。
Python dict() 関数 を作成するために使用されます Python辞書 、キーと値のペアのコレクション。
Python3
dict> (One> => '1'> , Two> => '2'> )> |
出力:
{'One': '1', 'Two': '2'} 例 1: キーワード引数を使用した辞書の作成
辞書のキーと値となる必要な値を含むパラメータとしてキーワード引数を渡すことができます。
構文:
dict(**kwarg)
Python3
# passing keyword arguments to dict() method> myDict> => dict> (a> => 1> , b> => 2> , c> => 3> , d> => 4> )> > print> (myDict)> |
出力:
{'a': 1, 'b': 2, 'c': 3, 'd': 4} 例 2 : dict() を使用して辞書のディープコピーを作成する
新しいインスタンスの作成 ( ディープコピー ) dict() を使用して辞書を作成します。
構文:
dict(mapping)
Python3
main_dict> => {> 'a'> :> 1> ,> 'b'> :> 2> ,> 'c'> :> 3> }> > # deep copy using dict> dict_deep> => dict> (main_dict)> > # shallow copy without dict> dict_shallow> => main_dict> > # changing value in shallow copy will change main_dict> dict_shallow[> 'a'> ]> => 10> print> (> 'After change in shallow copy, main_dict:'> , main_dict)> > # changing value in deep copy won't affect main_dict> dict_deep[> 'b'> ]> => 20> print> (> 'After change in deep copy, main_dict:'> , main_dict)> |
出力:
After change in shallow copy, main_dict: {'a': 10, 'b': 2, 'c': 3} After change in deep copy, main_dict: {'a': 10, 'b': 2, 'c': 3} 例 3: iterableを使用した辞書の作成
キーと値はリストやタプルのような反復可能な形式で dict() に渡して辞書を形成することができ、キーワード引数も dict() に渡すことができます。
構文:
dict(iterable, **kwarg)
Python3
# A list of key value pairs is passed and> # a keyword argument is also passed> myDict> => dict> ([(> 'a'> ,> 1> ), (> 'b'> ,> 2> ), (> 'c'> ,> 3> )], d> => 4> )> > print> (myDict)> |
出力:
{'a': 1, 'b': 2, 'c': 3, 'd': 4}