Dictionary Fundamentals
A dictionary in Python is represented by curly braces {} and stores data in key-value pairs. The structure uses a hash algorithm to compute memory addresses for storing key-value combinations. Since hash tables are non-contiguous, dictionaries cannot be sliced and their contents maintain no specific order based on insertion.
Dictionary keys must be hashable objects, meaning they must be immutable data types such as:
Values can store any type of data.
data_store = {
42: "answer",
"name": "zhang",
(10, 20): "coordinates",
"scores": [95, 88, 92],
True: {"nested": "value"}
}
print(data_store)
print(data_store[42])
print(data_store[True])
print(data_store["scores"])
print(data_store[(10, 20)])
# Note: True evaluates to 1 in numeric contexts
Adding Elements
Two primary methods exist for adding key-value pairs:
sample = {}
sample["artist"] = "picasso"
sample[0] = "genesis"
print(sample)
sample.setdefault("language")
print(sample)
sample.setdefault("language", "python")
print(sample)
When a key exists, the assignment performs an update; otherwise, it creates a new entry.
Removing Elements
Available removal methods include pop(), del, clear(), and popitem():
inventory = {
"apple": 5,
"banana": 3,
"cherry": 7,
"dates": [1, 2]
}
inventory.pop("apple")
removed_item = inventory.popitem() # Random removal
print(inventory)
del inventory["banana"]
print(inventory)
inventory.clear()
print(inventory)
Updating Elements
The update() method merges dictionaries:
profile = {"id": 123, "username": "alice", "role": "user"}
updates = {"id": 456, "username": "bob", "status": "active"}
profile.update(updates)
print(profile)
print(updates)
Existing keys are modified, while new keys are added.
Accessing Elements
Two approaches for value retrieval:
catalog = {
"book1": "python",
"book2": "java",
"book3": "javascript"
}
print(catalog["book1"])
print(catalog.get("book2"))
print(catalog.get("nonexistent")) # Returns None
print(catalog["missing"]) # Raises KeyError
Iteration Techniques
Multiple iteration patterns are available:
library = {
"title": "Deep Learning",
"author": "Ian Goodfellow",
"year": 2016,
"pages": 775
}
# Iterate over keys
for k in library.keys():
print(k)
# Iterate over values
for v in library.values():
print(v)
# Iterate over key-value pairs
for key, value in library.items():
print(f"{key}: {value}")
# Tuple unpacking example
info = ("data", "science", 2023)
field, specialty, year = info
print(field, specialty, year)
Nested Dictionaries
Complex data structures can be created through nesting:
company = {
"name": "TechCorp",
"founded": 2010,
"ceo": {
"name": "Sarah Chen",
"age": 45
},
"products": [
{"name": "CloudSync", "version": "2.0"},
{"name": "DataVault", "version": "1.5"}
]
}
# Access nested data
print(company["products"][1]["version"])
print(company["ceo"]["name"])
print(company["name"])
Advanced Dictionary Operations
Complex manipulations with nested structures:
project = {
"team": ["john", "mary", "bob"],
"budget": 50000,
"modules": {
"frontend": ["react", "redux"],
"backend": ["django", "postgresql"]
}
}
# Add team member
project["team"].append("alice")
print(project)
# Capitalize first member
project["team"][0] = project["team"][0].title()
print(project)
# Add new module
project["modules"]["devops"] = ["docker", "kubernetes"]
print(project)
# Remove backend technology
project["modules"]["backend"].remove("postgresql")
print(project)