Dictionary: dictionary methods and built-in functions

Dictionary: concept of key-value pair, creating, initializing, traversing, updating and deleting elements, dictionary methods and built-in functions – dict(), len(), keys(), values(), items(), update(), del, clear()

Class 11 Python: Dictionaries

Dictionaries are a versatile and powerful data structure in Python used to store data in key-value pairs. Each key is unique, and it maps to a specific value.

1. Concept of Key-Value Pair

A dictionary in Python consists of keys and values:

  • Key: A unique identifier for the value.
  • Value: The data associated with the key.

Example:

student = {
"name": "Alice",
"age": 17,
"grade": "A"
}

2. Creating and Initializing Dictionaries

  • Creating an Empty Dictionary:

    my_dict = {}
  • Creating a Dictionary with Initial Values:

    student = {
    "name": "Alice",
    "age": 17,
    "grade": "A"
    }
  • Using the dict() Constructor:

    student = dict(name="Alice", age=17, grade="A")
  • Creating a Dictionary from a List of Tuples:

    student = dict([("name", "Alice"), ("age", 17), ("grade", "A")])

3. Traversing Dictionaries

To access and print all key-value pairs in a dictionary:

  • Using a for Loop:

    student = {"name": "Alice", "age": 17, "grade": "A"}
    for key, value in student.items():
    print(f"{key}: {value}")
  • Using Dictionary Comprehension:

    student = {"name": "Alice", "age": 17, "grade": "A"}
    {key: value for key, value in student.items()}

4. Updating and Deleting Elements

  • Updating Elements: You can change the value associated with a key.

    student = {"name": "Alice", "age": 17, "grade": "A"}
    student["age"] = 18 # Update the age
  • Adding New Key-Value Pairs:

    student = {"name": "Alice", "age": 17}
    student["grade"] = "A" # Add new key-value pair
  • Deleting Elements:

    • Using del Keyword:

      student = {"name": "Alice", "age": 17, "grade": "A"}
      del student["grade"] # Remove the key-value pair with key "grade"
    • Using pop():


      student = {"name": "Alice", "age": 17, "grade": "A"}
      age = student.pop("age") # Remove and return the value associated with "age"
    • Using popitem():

      student = {"name": "Alice", "age": 17, "grade": "A"}
      item = student.popitem() # Remove and return the last key-value pair
    • Using clear():

      student = {"name": "Alice", "age": 17, "grade": "A"}
      student.clear() # Remove all key-value pairs

5. Dictionary Methods and Built-in Functions

  • dict(): Constructor to create a dictionary.

    d = dict(name="Alice", age=17)
  • len(): Returns the number of key-value pairs in the dictionary.

    student = {"name": "Alice", "age": 17}
    length = len(student) # Output: 2
  • keys(): Returns a view object displaying a list of all keys.

    student = {"name": "Alice", "age": 17}
    keys = student.keys() # Output: dict_keys(['name', 'age'])
  • values(): Returns a view object displaying a list of all values.

    student = {"name": "Alice", "age": 17}
    values = student.values() # Output: dict_values(['Alice', 17])
  • items(): Returns a view object displaying a list of key-value tuple pairs.

    student = {"name": "Alice", "age": 17}
    items = student.items() # Output: dict_items([('name', 'Alice'), ('age', 17)])
  • update(): Updates the dictionary with key-value pairs from another dictionary or iterable.

    student = {"name": "Alice"}
    student.update({"age": 17, "grade": "A"})
  • clear(): Removes all items from the dictionary.

    student = {"name": "Alice", "age": 17}
    student.clear() # Results in {}

Summary

  • Dictionaries store data in key-value pairs.
  • Creating dictionaries can be done using literals, the dict() constructor, or from lists of tuples.
  • Traversing involves iterating through key-value pairs.
  • Updating and deleting involve modifying or removing key-value pairs.
  • Dictionary methods provide various ways to interact with the dictionary, including retrieving keys, values, and items, as well as updating and clearing the dictionary.

Post a Comment

0 Comments