Dictionaries are a fundamental data structure in Python that allow us to store and organize data in a flexible and efficient manner. Unlike lists and tuples, which use an index-based approach, dictionaries use a key-value pairing system. In this article, we will explore dictionaries in Python, understand their properties, and demonstrate their usage through examples.

  1. Creating Dictionaries:

    • Example 1: Creating a dictionary using curly braces and key-value pairs

      student = {"name": "John", "age": 20, "major": "Computer Science"}
    • Example 2: Creating a dictionary using the dict() constructor and keyword arguments

      student = dict(name="John", age=20, major="Computer Science")
  2. Accessing Values:

    • Example 1: Accessing a value using the key

      student = {"name": "John", "age": 20, "major": "Computer Science"}

      print(student["name"])

      # Output: John
    • Example 2: Using the get() method to access a value with a default fallback

      student = {"name": "John", "age": 20, "major": "Computer Science"}

      print(student.get("gender", "Unknown"))

      # Output: Unknown
  3. Modifying and Adding Elements:

    • Example 1: Modifying a value by accessing it using the key

      student = {"name": "John", "age": 20, "major": "Computer Science"}

      student["age"] = 21

      print(student["age"])

      # Output: 21

    • Example 2: Adding a new key-value pair to the dictionary

      student = {"name": "John", "age": 20}

      student["major"] = "Computer Science"

      print(student)

      # Output: {'name': 'John', 'age': 20, 'major': 'Computer Science'}

  4. Iterating over Dictionaries:

    • Example: Iterating through the keys and values of a dictionary using a for loop

      student = {"name": "John", "age": 20, "major": "Computer Science"}

      for key, value in student.items():

        print(key, ":", value)

      # Output: # name : John # age : 20 # major : Computer Science

  5. Dictionary Methods:

    • Example: Using the keys(), values(), and items() methods
      student = {"name": "John", "age": 20, "major": "Computer Science"}

      print(student.keys())

      # Output: dict_keys(['name', 'age', 'major']) print(student.values())

      # Output: dict_values(['John', 20, 'Computer Science'])

      print(student.items())

      # Output: dict_items([('name', 'John'), ('age', 20), ('major', 'Computer Science')])

Conclusion: Dictionaries are a versatile and powerful data structure in Python, allowing us to store and retrieve data using key-value pairs. They offer fast access and efficient modification, making them suitable for various use cases. By mastering dictionaries, you can effectively organize and manipulate data, simplifying your code and enhancing your Python programming skills