Lesson 24 of 4060%

(Progress persistence is disabled until Phase 9)

Python
Beginner

Dictionary Methods

Common built-in methods for manipulating dictionaries.

Dictionary Methods

What You’ll Learn

You’ll learn how to iterate through dictionaries and manipulate their contents efficiently.

Extracting Data

  • keys(): Returns a list containing the dictionary’s keys.
  • values(): Returns a list of all the values in the dictionary.
  • items(): Returns a list containing a tuple for each key value pair.
user = {"name": "Alice", "age": 25}

print(user.keys())   # dict_keys(['name', 'age'])
print(user.values()) # dict_values(['Alice', 25])
print(user.items())  # dict_items([('name', 'Alice'), ('age', 25)])

Looping through Dictionaries

The items() method is particularly useful for looping.

for key, value in user.items():
    print(f"Key: {key}, Value: {value}")

Removing Items

  • pop(): Removes the item with the specified key name.
  • clear(): Empties the dictionary.
user.pop("age") # Removes the 'age' key/value pair

Lesson Progress

Practice This TopicTake QuizBuild a Python Project

Ready to practise?

Apply what you learned with a hands-on challenge.

Practise This Topic