🛠 Dictionary Methods
Last Updated: 17th August 2025
A dictionary stores key : value pairs. Keys are unique and immutable; values can be any type.
Below are the most important dictionary methods you must know — each shown with a short example and plain explanation.
- keys(): Returns a list of all the keys in the dictionary.
fruitsWithPrices = {"apple": 100, "banana": 50, "cherry": 75}
print(fruitsWithPrices.keys()) # dict_keys(['apple', 'banana', 'cherry'])
- values(): Returns a list of all the values in the dictionary.
fruitsWithPrices = {"apple": 100, "banana": 50, "cherry": 75}
print(fruitsWithPrices.values()) # dict_values([100, 50, 75])
- items(): Returns a list of all the (key, value) pairs in the dictionary.
fruitsWithPrices = {"apple": 100, "banana": 50, "cherry": 75}
print(fruitsWithPrices.items()) # dict_items([('apple', 100), ('banana', 50), ('cherry', 75)])
- get(): Returns the value for a given key, or a default value if the key is not found.
fruitsWithPrices = {"apple": 100, "banana": 50, "cherry": 75}
print(fruitsWithPrices.get("apple")) # 100
print(fruitsWithPrices.get("orange", 0)) # 0
- setdefault(): Returns the value for a given key, or a default value if the key is not found.
fruitsWithPrices = {"apple": 100, "banana": 50, "cherry": 75}
print(fruitsWithPrices.setdefault("apple")) # 100
print(fruitsWithPrices.setdefault("orange", 10)) # 10
- update(): Updates the dictionary with the given key-value pairs.
fruitsWithPrices = {"apple": 100, "banana": 50, "cherry": 75}
fruitsWithPrices.update({"apple": 200, "orange": 300})
print(fruitsWithPrices) # {'apple': 200, 'banana': 50, 'cherry': 75, 'orange': 300}
- pop(): Removes and returns the value for a given key, or a default value if the key is not found.
fruitsWithPrices = {"apple": 100, "banana": 50, "cherry": 75}
print(fruitsWithPrices.pop("apple")) # 100
print(fruitsWithPrices.pop("orange", 0)) # 0
- del: Removes a key from the dictionary. It raises a
KeyErrorif the key is not found.
fruitsWithPrices = {"apple": 100, "banana": 50, "cherry": 75}
del fruitsWithPrices["apple"]
- popitem(): Removes and returns the last inserted
(key, value)pair (Python 3.7+ preserve insertion order). RaisesKeyErrorif dict empty.
fruitsWithPrices = {"apple": 100, "banana": 50, "cherry": 75}
print(fruitsWithPrices.popitem()) # ('cherry', 75)
- clear(): Removes all elements from the dictionary.
fruitsWithPrices = {"apple": 100, "banana": 50, "cherry": 75}
fruitsWithPrices.clear()
💡 Quick Practice
- Create a dictionary of your favorite fruits and their prices.
- Access the value for a specific fruit.
- Update the price of a fruit.
- Loop through the dictionary and print each fruit and its price.
- Exercise