Python Dictionaries: Your Key to Organized Data


If you’ve been following along with my Python journey, you already know about strings and lists. Both are super useful, but sometimes you need a way to store data in pairs – something like a “word” and its “meaning”, or a “student” and their “marks”.
That’s where Python dictionaries come in!
What is a Dictionary?
A dictionary in Python is a collection of key-value pairs.
The key is like a unique label.
The value is the data attached to that label.
Think of it as a real dictionary: the word is the key, and its definition is the value.
# Example
student = {
"name": "Lucky",
"age": 21,
"course": "AI"
}
print(student)
Output:
{'name': 'Lucky', 'age': 21, 'course': 'AI'}
Why Use Dictionaries?
Quick lookups: Access values directly using keys.
Organized: Keeps data in pairs, making it easy to understand.
Flexible: Can store numbers, strings, lists, or even other dictionaries as values.
Creating a Dictionary
You can create a dictionary using curly braces {}
:
# Empty dictionary
my_dict = {}
# Dictionary with some data
fruits = {"apple": 2, "banana": 5, "orange": 3}
print(fruits)
Accessing Data
To get a value, use its key:
print(fruits["apple"]) # Output: 2
But be careful! If the key doesn’t exist, Python throws an error.
To avoid that, use .get()
:
print(fruits.get("mango")) # Output: None
Adding and Updating Data
You can easily add new pairs or update existing ones:
fruits["mango"] = 10 # Add new key-value pair
fruits["apple"] = 4 # Update value of 'apple'
print(fruits)
Removing Data
Dictionaries also allow you to remove pairs:
fruits.pop("banana") # Removes 'banana'
print(fruits)
fruits.clear() # Removes everything
print(fruits)
Useful Dictionary Methods
Here are a few handy ones:
student.keys() # All keys
student.values() # All values
student.items() # All key-value pairs
Wrap-Up 🎁
Dictionaries are powerful tools in Python for managing data in a structured way.
They store data as key-value pairs.
You can add, update, and remove items easily.
They make your code cleaner and more readable.
Next time you’re working on a project, ask yourself: “Would this data make more sense as a dictionary?” Chances are, the answer will be yes!
Subscribe to my newsletter
Read articles from Tammana Prajitha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
