Python で辞書が空かどうかを確認する方法

PythonPythonBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Python で辞書が空かどうかを判断する方法を学びます。この実験では、中括弧 {}dict() コンストラクタを使用して空の辞書を作成する方法を説明します。次に、len() 関数を使用して辞書内のキー - 値ペアの数を確認し、空の辞書を効果的に識別する方法を探ります。

最後に、この実験では、空の辞書がブールコンテキストでどのように評価されるかを示し、Python で空の辞書を操作および識別する方法を包括的に理解する手助けとなります。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ObjectOrientedProgrammingGroup(["Object-Oriented Programming"]) python/BasicConceptsGroup -.-> python/booleans("Booleans") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ObjectOrientedProgrammingGroup -.-> python/constructor("Constructor") subgraph Lab Skills python/booleans -.-> lab-559507{{"Python で辞書が空かどうかを確認する方法"}} python/dictionaries -.-> lab-559507{{"Python で辞書が空かどうかを確認する方法"}} python/build_in_functions -.-> lab-559507{{"Python で辞書が空かどうかを確認する方法"}} python/constructor -.-> lab-559507{{"Python で辞書が空かどうかを確認する方法"}} end

空の辞書について学ぶ

このステップでは、Python の空の辞書について学びます。辞書はキー - 値ペアのコレクションであり、空の辞書は単にキー - 値ペアを含まない辞書です。空の辞書を作成し、操作する方法を理解することは、多くのプログラミングタスクの基礎となります。

空の辞書を作成するには、中括弧 {} または dict() コンストラクタのいずれかを使用できます。実際にどのように行うか見てみましょう。

  1. LabEx 環境で VS Code エディタを開きます。

  2. ~/project ディレクトリに empty_dict.py という名前の新しいファイルを作成します。

    ~/project/empty_dict.py
  3. empty_dict.py ファイルに以下の Python コードを追加します。

    ## Creating an empty dictionary using curly braces
    empty_dict_1 = {}
    print("Empty dictionary 1:", empty_dict_1)
    
    ## Creating an empty dictionary using the dict() constructor
    empty_dict_2 = dict()
    print("Empty dictionary 2:", empty_dict_2)

    このコードは、異なる方法を使用して 2 つの空の辞書 empty_dict_1empty_dict_2 を作成します。その後、print() 関数を使用してこれらの辞書を表示します。

  4. ターミナルで以下のコマンドを使用して Python スクリプトを実行します。

    python ~/project/empty_dict.py

    以下の出力が表示されるはずです。

    Empty dictionary 1: {}
    Empty dictionary 2: {}

    この出力は、両方の方法が空の辞書を正常に作成したことを確認します。

空の辞書は、より複雑なデータ構造を構築するための出発点として便利です。必要に応じてキー - 値ペアを追加することができます。次のステップでは、辞書が空かどうかをチェックする方法と、空の辞書がブールコンテキストでどのように評価されるかを学びます。

len() を使って確認する

このステップでは、len() 関数を使って辞書が空かどうかを確認する方法を学びます。len() 関数は、辞書内の要素(キー - 値ペア)の数を返します。辞書が空の場合、len() は 0 を返します。

前のステップで作成した empty_dict.py ファイルを修正して、len() 関数を追加しましょう。

  1. VS Code エディタで empty_dict.py ファイルを開きます。

    ~/project/empty_dict.py
  2. empty_dict.py ファイル内の Python コードを修正して、len() 関数を追加します。

    ## Creating an empty dictionary using curly braces
    empty_dict_1 = {}
    print("Empty dictionary 1:", empty_dict_1)
    print("Length of empty_dict_1:", len(empty_dict_1))
    
    ## Creating an empty dictionary using the dict() constructor
    empty_dict_2 = dict()
    print("Empty dictionary 2:", empty_dict_2)
    print("Length of empty_dict_2:", len(empty_dict_2))
    
    ## Checking if a dictionary is empty using len()
    if len(empty_dict_1) == 0:
        print("empty_dict_1 is empty")
    else:
        print("empty_dict_1 is not empty")

    このコードは、len() を使って空の辞書の長さを計算し、結果を出力します。また、条件文で len() を使って辞書が空かどうかを確認する方法を示しています。

  3. ターミナルで以下のコマンドを使って Python スクリプトを実行します。

    python ~/project/empty_dict.py

    以下の出力が表示されるはずです。

    Empty dictionary 1: {}
    Length of empty_dict_1: 0
    Empty dictionary 2: {}
    Length of empty_dict_2: 0
    empty_dict_1 is empty

    この出力は、len() 関数が空の辞書に対して 0 を返し、条件文が辞書が空であることを正しく識別していることを確認します。

len() を使うことは、辞書にキー - 値ペアが含まれているかどうかを判断する簡単で効果的な方法です。これは、辞書が空かどうかに応じて異なるアクションを実行する必要があるなど、さまざまなシナリオで役立ちます。

ブール値として評価する

このステップでは、空の辞書がブールコンテキストでどのように評価されるかを学びます。Python では、特定の値は「真(truthy)」と見なされ(True と評価され)、他の値は「偽(falsy)」と見なされます(False と評価され)。これは、if 文のようなブールコンテキストで使用される場合です。空の辞書は「偽(falsy)」と見なされます。

この概念を実証するために、これまで作業していた empty_dict.py ファイルを修正しましょう。

  1. VS Code エディタで empty_dict.py ファイルを開きます。

    ~/project/empty_dict.py
  2. empty_dict.py ファイル内の Python コードを修正して、空の辞書のブール評価を含めます。

    ## Creating an empty dictionary using curly braces
    empty_dict_1 = {}
    print("Empty dictionary 1:", empty_dict_1)
    print("Length of empty_dict_1:", len(empty_dict_1))
    
    ## Creating an empty dictionary using the dict() constructor
    empty_dict_2 = dict()
    print("Empty dictionary 2:", empty_dict_2)
    print("Length of empty_dict_2:", len(empty_dict_2))
    
    ## Checking if a dictionary is empty using len()
    if len(empty_dict_1) == 0:
        print("empty_dict_1 is empty")
    else:
        print("empty_dict_1 is not empty")
    
    ## Evaluating an empty dictionary as a boolean
    if empty_dict_1:
        print("empty_dict_1 is truthy")
    else:
        print("empty_dict_1 is falsy")

    このコードは、empty_dict_1 変数を直接評価する if 文を追加しています。これは空の辞書なので、ブールコンテキストでは False として扱われます。

  3. ターミナルで以下のコマンドを使用して Python スクリプトを実行します。

    python ~/project/empty_dict.py

    以下の出力が表示されるはずです。

    Empty dictionary 1: {}
    Length of empty_dict_1: 0
    Empty dictionary 2: {}
    Length of empty_dict_2: 0
    empty_dict_1 is empty
    empty_dict_1 is falsy

    この出力は、空の辞書 empty_dict_1if 文で「偽(falsy)」と評価されることを確認します。

空の辞書が False と評価されることを理解することで、コードを簡素化し、読みやすくすることができます。辞書の長さを明示的にチェックすることなく、ブールコンテキストで直接辞書を使用することができます。

まとめ

この実験では、Python の空の辞書について学び、中括弧 {} または dict() コンストラクタを使用してそれらを作成する方法を学びました。empty_dict.py ファイルを作成し、print() 関数を使用して作成した空の辞書を表示し、両方の方法が空の辞書を正常に作成したことを確認しました。

この実験ではまた、辞書が空かどうかを確認するために len() 関数を使用する概念を紹介しました。この概念は、後続のステップでさらに詳しく説明されます。