Python Lesson 8: Dictionaries
PYTHON
AllComputerss
4/18/20261 min read


Dictionaries are one of Python’s most powerful and flexible data structures. They allow you to store data in key-value pairs, making it easy to organize and retrieve information efficiently.
What Are Dictionaries?
A dictionary is an unordered collection where each item consists of a key and a value. Keys must be unique and immutable (like strings or numbers), while values can be of any data type.
Creating Dictionaries
# Example of a dictionary
person = { "name": "Alice", "age": 25, "city": "Paris" }
print(person)
Accessing Values
You can access values by referencing their keys:
print(person["name"]) # Output: Alice
print(person["age"]) # Output: 25
Adding and Updating Items
Dictionaries are mutable, so you can add new key-value pairs or update existing ones:
person["email"] = "alice@example.com" # Add new key-value pair
person["age"] = 26 # Update existing value print(person)
Removing Items
You can remove items using del or the pop() method:
del person["city"]
print(person)
person.pop("email")
print(person)
Iterating Through Dictionaries
You can loop through keys, values, or both:
for key in person:
print(key, person[key])
for key, value in person.items():
print(f"{key}: {value}")
Useful Dictionary Methods
keys() → Returns all keys
values() → Returns all values
items() → Returns key-value pairs
get(key) → Safely retrieves a value without error if the key doesn’t exist
print(person.get("name")) # Output: Alice
print(person.keys()) # Output: dict_keys(['name', 'age'])
Why Use Dictionaries?
Fast lookups: Accessing values by keys is efficient.
Flexible storage: Values can be any type, including lists or other dictionaries.
Real-world use cases: Perfect for representing structured data like user profiles, configuration settings, or JSON objects.
Conclusion
Dictionaries are essential for organizing and managing data in Python. Their key-value structure makes them ideal for scenarios where quick lookups and structured information are needed. Mastering dictionaries will prepare you for working with more complex data formats and APIs.
© 2026 AllComputerss. All rights reserved.