Python Dictionary Methods 📖
Dictionary Methods Reference
Python dictionaries store data values in key:value pairs. These methods help you manipulate and query dictionary data.
✨ Most Commonly Used
python
# get() / keys() / values() / items()
person = {"name": "Alice", "age": 30}
print(person.get("name")) # "Alice"
print(person.get("city", "Unknown")) # Default value
print(person.keys()) # dict_keys(['name', 'age'])
print(person.values()) # dict_values(['Alice', 30])python
# update() / pop() / setdefault()
person.update({"city": "NYC", "age": 31})
removed = person.pop("age") # Returns 31
person.setdefault("country", "USA")
# If 'country' exists, returns value; else adds it📋 Complete Method Reference
| Method | Description |
|---|---|
| clear() | Removes all the elements from the dictionary |
| copy() | Returns a shallow copy of the dictionary |
| fromkeys() | Returns a dictionary with the specified keys and value |
| get() | Returns the value of the specified key (with optional default) |
| items() | Returns a view object containing tuples of (key, value) pairs |
| keys() | Returns a view object containing the dictionary's keys |
| pop() | Removes and returns the element with the specified key |
| popitem() | Removes and returns the last inserted key-value pair (as a tuple) |
| setdefault() | Returns the value of the specified key. If the key does not exist: insert the key with the specified value |
| update() | Updates the dictionary with the specified key-value pairs |
| values() | Returns a view object containing all the values in the dictionary |
✨ Pro Tip
Use get() instead of bracket notation when you're unsure if a key exists. It returns None (or a default value) instead of raising a KeyError.