A dictionary in Python is a collection of key–value pairs. Each key must be unique and is used to access its corresponding value. Dictionaries are:
{} with key: value pairs.get() method.Basic syntax to create a dictionary:
# General form
dictionary_name = {
key1: value1,
key2: value2,
key3: value3
}
# Example
person = {"name": "Alice", "age": 25, "city": "New York"}
Dictionaries can also be created using the dict() constructor, but using curly braces is the most common and readable approach.
You can create a dictionary using curly braces with key–value pairs.
person = {"name": "Alice", "age": 25, "city": "New York"}
print(person)
# {'name': 'Alice', 'age': 25, 'city': 'New York'}
Access dictionary values using their keys. Use square brackets when you are sure the key exists, or get() when the key might be missing.
print(person["name"]) # Alice
print(person.get("age")) # 25
You can add a new key–value pair or update an existing key simply by assigning to that key.
person["email"] = "alice@example.com" # Add new
person["age"] = 26 # Update existing
print(person)
# {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}
Remove items using pop(), popitem(), or del.
person.pop("city") # Remove by key
person.popitem() # Remove last inserted item
del person["age"] # Delete by key
print(person)
# {'name': 'Alice'}
Starting with:
# Initial dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}
After adding email and updating age:
person["email"] = "alice@example.com" # Add a new key-value pair
person["age"] = 26 # Update the existing 'age' key
print(person) # Print the updated dictionary
Output:
# Updated dictionary after changes
{'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}
Notice how the value of "age" changed from 25 to 26, and a new key "email" was added. This shows that dictionaries are both mutable and dynamic.
Use dictionaries when you need:
get() to safely access keys that might not exist, e.g. person.get("phone")."name", "age", etc.KeyError (use get() or in checks).get() for a key that might not exist.pop() and print the updated dictionary.