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!
🔴 Live TV: sameerqaiser/python dictionaries methods you should actually be using l - Pertandingan Hari Ini 🔴 Live TV: sameerqaiser/python dictionaries methods you should actually be using l - Pertandingan Hari Ini

Do this:

print(user.get("age", "Not found"))
🔴 Live TV: sameerqaiser/python dictionaries methods you should actually be using l - Pertandingan Hari Ini 🔴 Live TV: sameerqaiser/python dictionaries methods you should actually be using l - Pertandingan Hari Ini

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

user = {"name": "Ali", "age": 25}
for key, value in user.items():
    print(f"{key}: {value}")
🔴 Live TV: sameerqaiser/python dictionaries methods you should actually be using l - Pertandingan Hari Ini 🔴 Live TV: sameerqaiser/python dictionaries methods you should actually be using l - Pertandingan Hari Ini

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

print(user.keys()) 
print(user.values()) 
🔴 Live TV: sameerqaiser/python dictionaries methods you should actually be using l - Pertandingan Hari Ini 🔴 Live TV: sameerqaiser/python dictionaries methods you should actually be using l - Pertandingan Hari Ini

4. .pop()- Remove and Return

age = user.pop("age")
print(age)
🔴 Live TV: sameerqaiser/python dictionaries methods you should actually be using l - Pertandingan Hari Ini 🔴 Live TV: sameerqaiser/python dictionaries methods you should actually be using l - Pertandingan Hari Ini

5. dict.update()-Merge Dictionaries

user.update({"city": "Karachi"})
print(user)
🔴 Live TV: sameerqaiser/python dictionaries methods you should actually be using l - Pertandingan Hari Ini 🔴 Live TV: sameerqaiser/python dictionaries methods you should actually be using l - Pertandingan Hari Ini

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)