Dictionaries
Key–value pairs — the structure behind most real-world data in Python.
A dictionary stores key–value pairs. Keys must be unique and hashable (strings, numbers, and tuples of immutables all work); values can be anything.
channel = {
"name": "CodeWithMunnaX",
"subscribers": 250_000,
"verified": True,
}
print(channel["name"]) # 'CodeWithMunnaX'
channel["subscribers"] += 1000 # update a value
channel["platform"] = "YouTube" # add a new key
Avoiding KeyError
Indexing with [] raises KeyError if the key doesn't exist. .get() returns None (or a default you provide) instead.
print(channel.get("platform", "Unknown")) # 'YouTube'
print(channel.get("country", "Unknown")) # 'Unknown' -- no KeyError
Iterating a dictionary
for key in channel: # iterates keys by default
print(key)
for key, value in channel.items(): # the one you'll use most
print(key, "->", value)
for value in channel.values():
print(value)
Since Python 3.7, dictionaries preserve insertion order — iterating gives you keys in the order they were added, not a random order.
Removing keys
channel.pop("verified") # remove and return the value
del channel["platform"] # remove without returning it
Merging dictionaries
defaults = {"theme": "dark", "autoplay": True}
overrides = {"autoplay": False}
settings = {**defaults, **overrides} # later keys win on conflict
print(settings) # {'theme': 'dark', 'autoplay': False}Key points to remember
- •dict[key] raises KeyError for a missing key; dict.get(key, default) doesn't.
- •Dictionaries have preserved insertion order since Python 3.7 — iteration order matches how keys were added.
- •for k, v in d.items(): is the standard way to loop over both keys and values together.
- •{**a, **b} merges dictionaries; when both have the same key, the value from the later one wins.
- •Keys must be hashable (immutable) — strings, numbers, and tuples of immutables work; lists and dicts don't.
Building and reading a channel profile
Revision Flashcards
Tap a card to flip it and see the answer.