Dictionaries are an essential data structure in Python that allow you to store and retrieve data using key-value pairs. They provide a powerful way to organize and manipulate data efficiently. In this article, we will explore how to create dictionaries and perform various operations on them. We will also cover different methods to iterate through dictionaries using loops. By the end, you will have a solid understanding of creating dictionaries and effectively looping through them.

  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")
    • Example 3: Creating a dictionary using the zip() function

      keys = ["name", "age", "major"]

      values = ["John", 20, "Computer Science"]

      student = dict(zip(keys, values))
  2. Looping Through Dictionaries:

    • Example 1: Looping through keys using a for loop

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

      for key in student:

          print(key) # Output: name, age, major

       
    • Example 2: Looping through values using the values() method

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

      for value in student.values():

         print(value) # Output: John, 20, Computer Science
    • Example 3: Looping through key-value pairs using the items() method

      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

  3. Modifying and Adding Elements:

    • Example: 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

  4. Removing Elements:

    • Example: Removing a key-value pair using the del keyword
      student = {"name": "John", "age": 20, "major": "Computer Science"}

      del student["age"]

      print(student)

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

Conclusion: Dictionaries are a powerful data structure in Python that allow you to store and access data using key-value pairs. In this article, we explored different methods to create dictionaries and how to loop through them using for loops. We also covered modifying and removing elements from dictionaries. By mastering dictionaries and their operations, you will have a solid foundation for working with complex data structures and efficiently managing data in your Python programs.