Introduction
When I first learned about Python dictionaries, I just used them to store key-value pairs. But there are a few built-in methods that save so much time and make your code cleaner.
Here are the 5 methods I use almost every day.
1. .get() - The Safe Way to Access Keys
Instead of this:
user = {"name": "Ali"}
print(user["age"]) # KeyError!
Do this:
print(user.get("age", "Not found"))
2. .items()-Loop Through Keys and Values
user = {"name": "Ali", "age": 25}
for key, value in user.items():
print(f"{key}: {value}")
3. Keys() and .values()-Just the Basics
print(user.keys())
print(user.values())
4. .pop()- Remove and Return
age = user.pop("age")
print(age)
5. dict.update()-Merge Dictionaries
user.update({"city": "Karachi"})
print(user)
Conclusion
Dictionaries are powerful. Once you stop using brackets for everything and start using these methods, your python code will be much safer and more readable.
Top comments (0)