What are Dictionaries?
A Dictionary lets you store information in key-value pairs. Instead of finding items by numbered positions like 0 or 1, you look up values using unique labels called keys.
Think of a dictionary like:
- A contact book (Name -> Phone Number)
- A restaurant menu (Dish Name -> Price)
- A user profile (Username -> Email Address)
Creating a Dictionary
You create a dictionary using curly braces {} with a colon : separating each key from its value:
user = {
"name": "Alice",
"age": 25,
"is_admin": True
}
Accessing Values by Key
To read a value, write the dictionary name followed by the key label inside square brackets []:
user = {"name": "Alice", "age": 25}
print(user["name"]) # Output: Alice
print(user["age"]) # Output: 25
Adding and Updating Values
If you assign a value to a key that already exists, Python updates the value. If the key does not exist yet, Python creates a brand new key-value pair:
user = {"name": "Alice"}
# Update existing key
user["name"] = "Alice Smith"
# Add a brand new key
user["email"] = "alice@example.com"
print(user)
# Output: {'name': 'Alice Smith', 'email': 'alice@example.com'}
Removing Key-Value Pairs (del, pop)
del my_dict["key"]deletes the key and value completely..pop("key")deletes the key and returns the value so you can store or inspect it.
user = {"name": "Alice", "role": "editor", "points": 100}
# Delete points
del user["points"]
# Pop out role
user_role = user.pop("role")
print(f"Removed role: {user_role}")
print(user) # Output: {'name': 'Alice'}
Common Beginner Mistakes
KeyErroron Missing Keys: Looking up a key that does not exist (user["phone"]) crashes Python.- Fix: Use
"phone" in userto check first, or use.get("phone")for safe lookup.
Quick Summary
- Dictionary Definition: A collection of
key: valuemappings enclosed in curly braces{...}. - Key Rules: Keys must be unique and immutable (strings, integers, tuples); values can be any data type.
- Access & Mutation: Access using
dict[key]; create or update values usingdict[key] = new_value. - Fast Lookup: Dictionaries use hash tables for lightning-fast $O(1)$ key lookups.
What's Next?
Let's explore dictionary inspection methods like .get(), .keys(), .values(), and .items() in the next lesson!