Python Basics
Python Dictionaries
1. What is a Dictionary?
A dictionary stores key-value pairs. You look up values using their keys — similar to how a list uses indices, except you define your own keys.
x = {2: "hello", "one": 5}
- Keys and values can be any data type (int, string, tuple, etc.)
- Keys and values don't need to be consistent types
- Dictionaries are unordered — don't rely on insertion order
2. Creating a Dictionary
With initial values
x = {2: "hello", "one": 5}
Empty dictionary
x = {}
x = dict()
3. Accessing Values
Use square brackets with the key.
x = {2: "hello", "one": 5}
x[2] # → "hello"
x["one"] # → 5
⚠️ Accessing a key that doesn't exist raises a
KeyError.
4. Adding & Updating Items
x["key"] = "value" # adds new key-value pair
x[2] = "world" # updates existing key (overrides old value)
- If the key doesn't exist → it gets added
- If the key already exists → its value gets overwritten
5. Deleting Items
Use the del keyword.
del x[2] # removes the key 2 and its value entirely
6. Checking if a Key Exists
The in operator checks for keys only (not values).
1 in x # → True if key 1 exists
1 not in x
7. Useful Methods
.values() — get all values
x.values() # → dict_values([...])
list(x.values()) # convert to a regular list
.keys() — get all keys
x.keys() # → dict_keys([...])
list(x.keys()) # convert to a regular list
.items() — get all key-value pairs as tuples
x.items() # → dict_items([(key, value), ...])
list(x.items()) # → [(key, value), ...]
.get(key, default) — safe lookup with fallback ⭐
x.get(4, 0) # returns value at key 4, or 0 if key doesn't exist
Avoids a KeyError when the key might not be present.
8. Length
len(x) # number of key-value pairs
9. Looping Through a Dictionary
By key (then access value manually)
for key in x:
value = x[key]
print(key, value)
By key and value together (preferred)
for key, value in x.items():
print(key, value)
Since dictionaries are unordered, you cannot loop by index using
range.
10. Common Pattern — Frequency Counting
Use .get() to count occurrences without crashing on missing keys.
Count characters in a string
string = "hello world"
characters = {}
for char in string:
characters[char] = characters.get(char, 0) + 1
print(characters)
# → {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
Count user inputs
counts = {}
while True:
num = input("Enter a number (q to quit): ")
if num == "q":
break
num = int(num)
counts[num] = counts.get(num, 0) + 1
print(counts)
11. Dictionary vs List — Lookup Speed
| Operation | List | Dictionary |
|---|---|---|
| Check if item exists | Slow — scans every element | Instant |
| Access by key/index | Fast (by index) | Instant (by key) |
| Insert item | Fast | Instant |
Rule of thumb: If you need to frequently check whether something exists, use a dictionary over a list.
A list must scan every item one by one to find a match. A dictionary looks it up instantly regardless of size.
Cheat Sheet
# Create
d = {"a": 1, "b": 2}
d = {}
# Access
d["a"] # → 1 (KeyError if missing)
d.get("a", 0) # → 1, or 0 if missing
# Add / Update
d["c"] = 3 # add or overwrite
# Delete
del d["a"]
# Check key
"b" in d # → True
# Length
len(d) # → number of pairs
# Loop
for key in d: ...
for key, val in d.items(): ...
# All keys / values / pairs
d.keys()
d.values()
d.items()
# Frequency count pattern
d[key] = d.get(key, 0) + 1