Python Data Structures: Dictionaries 📖

A dictionary in Python is an unordered collection of key-value pairs. It allows fast lookups and modifications using keys. Unlike lists and tuples, dictionaries do not have an index—instead, they use unique keys to access values.
1️⃣ Creating Dictionaries
🔹 Basic Dictionary Syntax
Dictionaries are defined using curly braces {} with key-value pairs separated by colons :.
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
🔹 Creating a Dictionary with dict() Constructor
person = dict(name="Alice", age=25, city="New York")
print(person)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
🔹 Empty Dictionary
empty_dict = {}
print(empty_dict) # Output: {}
2️⃣ Accessing Dictionary Elements
🔹 Accessing Values by Key
person = {"name": "Alice", "age": 25, "city": "New York"}
print(person["name"]) # Output: Alice
print(person["age"]) # Output: 25
⚠️ If a key does not exist, it raises a KeyError.
🔹 Using get() to Avoid Errors
print(person.get("city")) # Output: New York
print(person.get("gender")) # Output: None (instead of an error)
3️⃣ Adding & Modifying Key-Value Pairs
🔹 Adding a New Key-Value Pair
person["gender"] = "Female"
print(person)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'gender': 'Female'}
🔹 Modifying an Existing Value
person["age"] = 26
print(person["age"]) # Output: 26
4️⃣ Removing Elements from a Dictionary
Method Description
del dict[key] Deletes a specific key
pop(key) Removes a key and returns its value
popitem() Removes the last inserted key-value pair
clear() Removes all elements
🔹 Examples
person = {"name": "Alice", "age": 25, "city": "New York"}
# Remove a specific key
del person["city"]
print(person) # Output: {'name': 'Alice', 'age': 25}
# Remove and return a value
age = person.pop("age")
print(age) # Output: 25
print(person) # Output: {'name': 'Alice'}
# Remove the last inserted item (Python 3.7+)
person["gender"] = "Female"
print(person.popitem()) # Output: ('gender', 'Female')
# Remove all elements
person.clear()
print(person) # Output: {}
5️⃣ Dictionary Methods
Method Description
keys() Returns all keys
values() Returns all values
items() Returns all key-value pairs as tuples
update(dict2) Merges another dictionary
copy() Creates a shallow copy
🔹 Examples
person = {"name": "Alice", "age": 25, "city": "New York"}
# Get all keys
print(person.keys()) # Output: dict_keys(['name', 'age', 'city'])
# Get all values
print(person.values()) # Output: dict_values(['Alice', 25, 'New York'])
# Get all key-value pairs
print(person.items()) # Output: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])
# Merge another dictionary
extra_info = {"gender": "Female", "job": "Engineer"}
person.update(extra_info)
print(person)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'gender': 'Female', 'job': 'Engineer'}
6️⃣ Dictionary Comprehension (One-Line Dictionary Creation)
squares = {x: x**2 for x in range(1, 6)}
print(squares)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
7️⃣ Checking If a Key Exists
person = {"name": "Alice", "age": 25}
if "name" in person:
print("Key exists!") # Output: Key exists!
if "salary" not in person:
print("Key does not exist!") # Output: Key does not exist!
8️⃣ Nested Dictionaries (Dictionaries Inside Dictionaries)
students = {
"Alice": {"age": 25, "city": "New York"},
"Bob": {"age": 23, "city": "Los Angeles"}
}
print(students["Alice"]["city"]) # Output: New York
When to Use Dictionaries?
✅ When you need fast lookups based on unique keys.
✅ When you want to store related information together (e.g., user profiles).
✅ When order doesn’t matter (although Python 3.7+ maintains insertion order).
Date: 2025-03-22 00:00:00.000000