Table of Contents
TogglePython dictionaries come with powerful built-in methods to manipulate and manage data. In this lesson, you’ll explore 12 essential dictionary methods—from clearing dictionaries to updating them. Let’s dive into these tools!
Below are the core methods of the dict class, with examples to show them in action.
d = {"a": 1, "b": 2}
d.clear()
print(d)
Output: {}
d = {"a": 1, "b": 2}
d2 = d.copy()
print(d2)
Output: {‘a’: 1, ‘b’: 2}
keys = ["a", "b"] d = dict.fromkeys(keys, 0) print(d)
Output: {‘a’: 0, ‘b’: 0}
d = {"a": 1}
print(d.get("a", 0))
print(d.get("b", 0))
Output: 1, 0
d = {"a": 1, "b": 2}
print(d.items())
Output: dict_items([(‘a’, 1), (‘b’, 2)])
d = {"a": 1, "b": 2}
print(d.keys())
Output: dict_keys([‘a’, ‘b’])
d = {"a": 1, "b": 2}
d.pop("a")
print(d)
Output: {‘b’: 2}
d = {"a": 1, "b": 2}
d.popitem()
print(d)
Output: {‘a’: 1}
d = {"a": 1}
d.setdefault("b", 0)
print(d)
Output: {‘a’: 1, ‘b’: 0}
d = {"a": 1}
d.update({"b": 2})
print(d)
Output: {‘a’: 1, ‘b’: 2}
d = {"a": 1, "b": 2}
print(d.values())
Output: dict_values([1, 2])
Key Takeaway: These methods—clear(), copy(), get(), and more—give you full control over dictionaries. Practice them to manage data like a pro!
Note: has_key() is not included as it’s deprecated in Python 3—use in (e.g., "key" in dict) instead.
