DEV Community

Sameer Qaiser
Sameer Qaiser

Posted on

Python Dictionaries: 5 Methods You Should Actually Be Using

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!
Enter fullscreen mode Exit fullscreen mode

Do this:

print(user.get("age", "Not found"))
Enter fullscreen mode Exit fullscreen mode

2. .items()-Loop Through Keys and Values

user = {"name": "Ali", "age": 25}
for key, value in user.items():
    print(f"{key}: {value}")
Enter fullscreen mode Exit fullscreen mode

3. Keys() and .values()-Just the Basics

print(user.keys()) 
print(user.values()) 
Enter fullscreen mode Exit fullscreen mode

4. .pop()- Remove and Return

age = user.pop("age")
print(age)
Enter fullscreen mode Exit fullscreen mode

5. dict.update()-Merge Dictionaries

user.update({"city": "Karachi"})
print(user)
Enter fullscreen mode Exit fullscreen mode

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)