Dictionaries are Python’s way of storing data as key-value pairs. Think of them like a real dictionary where you look up a word (key) to find its definition (value).
Creating Dictionaries
Use curly braces to create dictionaries:
student = {
"name": "Alice",
"age": 20,
"major": "Computer Science"
}
# Empty dictionary
empty_dict = {}
Accessing Dictionary Values
Use keys to access their corresponding values:
print(student["name"]) # Alice
print(student["age"]) # 20
# Safe access with get()
print(student.get("grade", "Not found")) # Not found
Modifying Dictionaries
Add new key-value pairs or update existing ones:
# Add new items
student["grade"] = "A"
student["year"] = "Junior"
# Update existing items
student["age"] = 21
# Remove items
del student["year"]
removed_grade = student.pop("grade")
Dictionary Methods
Useful methods for working with dictionaries:
# Get all keys, values, or items
print(student.keys()) # dict_keys(['name', 'age', 'major'])
print(student.values()) # dict_values(['Alice', 21, 'Computer Science'])
print(student.items()) # dict_items([('name', 'Alice'), ...])
Looping Through Dictionaries
# Loop through keys
for key in student:
print(f"{key}: {student[key]}")
# Loop through key-value pairs
for key, value in student.items():
print(f"{key}: {value}")
# Loop through values only
for value in student.values():
print(value)
Practical Example
# Count word occurrences
text = "hello world hello python"
word_count = {}
for word in text.split():
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count) # {'hello': 2, 'world': 1, 'python': 1}
Dictionaries are perfect for storing related information and creating lookups in your programs.