辞書 Python では、データ値の順序付けされていないコレクションであり、マップのようにデータ値を保存するために使用されます。要素として 1 つの値のみを保持する他のデータ型とは異なり、Dictionary は要素として保持します。 キー:値 ペア。ディクショナリをより最適化するために、キーと値がディクショナリに提供されます。
次に、空の辞書を作成するさまざまな方法を見てみましょう。
方法 1: の使用 { } シンボル。
代入ステートメント内で中括弧内の要素を指定しないことにより、空の辞書オブジェクトを作成できます。
コード:
Python3
# Python3 code to demonstrate use of> # {} symbol to initialize dictionary> emptyDict>=> {}> # print dictionary> print>(emptyDict)> # print length of dictionary> print>(>'Length:'>,>len>(emptyDict))> # print type> print>(>type>(emptyDict))> |
>
>出力
{} Length: 0> 方法 2: の使用 dict() 組み込み関数。
空の辞書は、引数なしの dict() 組み込み関数によっても作成されます。
コード:
Python3
# Python3 code to demonstrate use of> # dict() built-in function to> # initialize dictionary> emptyDict>=> dict>()> # print dictionary> print>(emptyDict)> # print length of dictionary> print>(>'Length:'>,>len>(emptyDict))> # print type> print>(>type>(emptyDict))> |
>
>出力
{} Length: 0> 方法 3 : 辞書を初期化する
段階的なアプローチ:
- 「emptyDict」という名前の空の辞書を初期化します。
- 「emptyDict」辞書を初期化します。辞書内包表記は、1 行のコードを使用して Python で辞書を作成する簡潔な方法です。この場合、反復処理するキーと値のペアがないため、内包表記は空になります。したがって、空のリストが理解に渡されます。結果は空の辞書になります。
- 結果の辞書を印刷します。
- 「len()」関数を使用して辞書の長さを出力し、 「type()」関数 。
Python3
# Python3 code to demonstrate initializing> # dictionary using dictionary comprehension> # Using dictionary comprehension> emptyDict>=> {key: value>for> key, value>in> []}> # print dictionary> print>(emptyDict)> # print length of dictionary> print>(>'Length:'>,>len>(emptyDict))> # print type> print>(>type>(emptyDict))> |
>
プッシュ用の git コマンド
>出力
{} Length: 0> 時間の複雑さ: 辞書内包を使用して空の辞書を初期化しているため、このメソッドの時間計算量は O(1) であり、一定の時間がかかります。
空間の複雑さ: 辞書のサイズに関係なく、メモリ内の固定量の領域を占有する空の辞書を初期化しているため、このメソッドの領域複雑さも O(1) です。