In Python, a dictionary is one of the most powerful and flexible data structures. It allows you to store data in key-value pairs, where each key must be unique, and values can be of any data type. Dictionaries are extremely useful for organizing data, improving code readability, and performing quick lookups. In this tutorial, we will explore Python dictionaries in detail, complete with examples and best practices.
What is a Python Dictionary?
A dictionary in Python is defined using curly braces {}, with each key-value pair separated by a colon :. You can think of it as a real-world dictionary, where the word is the key and its meaning is the value.
# Example of a Python dictionary student = { "name": "Alice", "age": 21, "major": "Computer Science" } print(student)
Output:
{'name': 'Alice', 'age': 21, 'major': 'Computer Science'}
Here, name, age, and major are keys, and their corresponding values are “Alice”, 21, and “Computer Science”.
Accessing Dictionary Values
You can access dictionary values using their keys within square brackets [] or using the get() method.
print(student["name"]) # Output: Alice
print(student.get("major")) # Output: Computer Science
If you try to access a key that doesn’t exist using [], Python raises a KeyError. However, get() returns None instead of throwing an error, making it safer for optional keys.
Adding and Updating Dictionary Elements
Dictionaries are mutable, meaning you can change their content after creation. You can add new key-value pairs or update existing ones easily.
# Add a new key-value pair student["grade"] = "A" # Update existing key student["age"] = 22 print(student)
Output:
{'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'grade': 'A'}
Removing Elements from a Dictionary
You can remove items using several methods such as pop(), del, and clear().
# Remove by key
student.pop("grade")
# Remove a specific key-value pair
del student["major"]
# Clear all items
student.clear()
print(student)
Output:
{}
Looping Through a Dictionary
Python provides different ways to loop through keys, values, or both.
student = {"name": "Alice", "age": 22, "major": "Computer Science"}
# Loop through keys
for key in student:
print(key)
# Loop through values
for value in student.values():
print(value)
# Loop through both keys and values
for key, value in student.items():
print(f"{key}: {value}")
Dictionary Methods
Here are some commonly used dictionary methods in Python:
keys()– returns all keys in the dictionaryvalues()– returns all valuesitems()– returns key-value pairs as tuplesupdate()– merges another dictionary or updates existing keyscopy()– creates a shallow copy of the dictionary
info = {"brand": "Toyota", "year": 2020}
extra = {"color": "blue", "type": "SUV"}
info.update(extra)
print(info)
Output:
{'brand': 'Toyota', 'year': 2020, 'color': 'blue', 'type': 'SUV'}
Dictionary Comprehension
Python allows you to create dictionaries using dictionary comprehensions — a concise way to generate dictionaries from iterable data.
squares = {x: x*x for x in range(1, 6)}
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Nested Dictionaries
A dictionary can also contain another dictionary as a value. This is useful for representing structured data such as JSON objects or configuration files.
students = {
"student1": {"name": "Alice", "age": 21},
"student2": {"name": "Bob", "age": 23}
}
print(students["student2"]["name"]) # Output: Bob
Real-World Example: Counting Word Frequency
Dictionaries are great for counting occurrences of items. Here’s a practical example that counts word frequency in a sentence:
sentence = "python dictionary explained with examples python tutorial" words = sentence.split() frequency = {} for word in words: frequency[word] = frequency.get(word, 0) + 1 print(frequency)
Output:
{'python': 2, 'dictionary': 1, 'explained': 1, 'with': 1, 'examples': 1, 'tutorial': 1}
Conclusion
Python dictionaries are versatile and essential for modern programming. Whether you’re building APIs, managing data, or working with JSON, understanding how dictionaries work will make your code cleaner and more efficient. Mastering this data structure is a must for every Python developer.
Now that you’ve learned how to use dictionaries, try combining them with lists and sets for even more powerful data handling.