Python Dictionary Methods
What Are Dictionary Methods?
Dictionary methods are built-in functions in Python that help you access, modify, update, and manage dictionaries efficiently.
Commonly Used Dictionary Methods
Method | Description |
---|---|
clear() | Removes all items from the dictionary |
copy() | Returns a shallow copy of the dictionary |
fromkeys() | Creates a new dictionary from keys |
get() | Returns the value for a key |
items() | Returns a view object of key-value pairs |
keys() | Returns a view object of all keys |
pop() | Removes item by key and returns its value |
popitem() | Removes the last inserted key-value pair |
setdefault() | Returns value for key; inserts if missing |
update() | Updates the dictionary with another |
values() | Returns a view object of all values |
Method Examples
1. clear()
person = {"name": "Alice", "age": 25}
person.clear()
print(person)
Output:
{}
2. copy()
person = {"name": "Bob", "age": 30}
new_person = person.copy()
print(new_person)
Output:
{'name': 'Bob', 'age': 30}
3. fromkeys()
keys = ["name", "age"]
default_dict = dict.fromkeys(keys, "unknown")
print(default_dict)
Output:
{'name': 'unknown', 'age': 'unknown'}
4. get()
person = {"name": "Charlie"}
print(person.get("name")) # Existing key
print(person.get("age", 0)) # Missing key with default
Output:
Charlie
0
5. items()
person = {"name": "Dave", "age": 22}
print(person.items())
Output:
dict_items([('name', 'Dave'), ('age', 22)])
6. keys()
and values()
person = {"name": "Dave", "age": 22}
print(person.keys()) # dict_keys(['name', 'age'])
print(person.values()) # dict_values(['Dave', 22])
7. pop()
person = {"name": "Dave", "age": 22}
age = person.pop("age")
print(age) # 22
print(person) # {'name': 'Dave'}
8. popitem()
person = {"name": "Dave", "age": 22}
last_item = person.popitem()
print(last_item)
Output:
('name', 'Dave')
9. setdefault()
person = {"name": "Eve"}
age = person.setdefault("age", 20)
print(person) # {'name': 'Eve', 'age': 20}
10. update()
person = {"name": "Eve"}
person.update({"name": "Eva", "city": "Paris"})
print(person)
Output:
{'name': 'Eva', 'age': 20, 'city': 'Paris'}
Tips
- Use
get()
when unsure if the key exists to avoid errors. setdefault()
is useful for setting default values during data cleaning.update()
is great for merging or adding multiple key-value pairs.
Conclusion
Python dictionaries come with powerful methods to manage data effectively. Learning these methods helps you write clean and efficient code.