PY

Dictionaries

Python · 8 entries

Creating Dictionaries

syntax
d = {key: value, ...}
d = dict(key=value, ...)
example
user = {"name": "Alice", "age": 30, "active": True}
from_pairs = dict(host="localhost", port=8080)
print(user)
print(from_pairs)
output
{'name': 'Alice', 'age': 30, 'active': True}
{'host': 'localhost', 'port': 8080}

Note Keys must be hashable (strings, numbers, tuples of hashables). Lists and dicts cannot be keys.

Accessing & Modifying Values

syntax
d[key]
d[key] = value
example
config = {"debug": False, "port": 3000}
print(config["port"])
config["debug"] = True
config["host"] = "0.0.0.0"
print(config)
output
3000
{'debug': True, 'port': 3000, 'host': '0.0.0.0'}

Note Accessing a missing key with d[key] raises KeyError. Use d.get(key) to safely return None instead.

get() with Default Value

syntax
d.get(key, default)
example
settings = {"theme": "dark"}
theme = settings.get("theme", "light")
lang = settings.get("language", "en")
print(theme, lang)
output
dark en

Note get() returns the default when the key is missing but does NOT add it to the dict. Use setdefault() if you want to also store the default.

Dictionary Methods

syntax
d.keys() / d.values() / d.items()
example
scores = {"alice": 95, "bob": 82, "carol": 91}
print(list(scores.keys()))
print(list(scores.values()))

for name, score in scores.items():
    print(f"{name}: {score}")
output
['alice', 'bob', 'carol']
[95, 82, 91]
alice: 95
bob: 82
carol: 91

Note keys(), values(), and items() return view objects that reflect changes to the dict in real time.

Dictionary Comprehensions

syntax
{key_expr: val_expr for item in iterable if condition}
example
words = ["hello", "world", "python"]
lengths = {w: len(w) for w in words}
print(lengths)

original = {"a": 1, "b": 2, "c": 3}
filtered = {k: v for k, v in original.items() if v >= 2}
print(filtered)
output
{'hello': 5, 'world': 5, 'python': 6}
{'b': 2, 'c': 3}

Note Dict comprehensions are great for transforming or filtering dictionaries in a single expression.

Merging Dictionaries (| Operator)

syntax
merged = d1 | d2
d1 |= d2  # in-place
example
defaults = {"color": "blue", "size": "medium"}
overrides = {"size": "large", "bold": True}
final = defaults | overrides
print(final)
output
{'color': 'blue', 'size': 'large', 'bold': True}

Note The | operator (Python 3.9+) creates a new dict. Right-hand side wins on duplicate keys. Use |= to merge in place.

defaultdict

syntax
from collections import defaultdict
dd = defaultdict(factory)
example
from collections import defaultdict

word_count = defaultdict(int)
for word in "the cat sat on the mat".split():
    word_count[word] += 1
print(dict(word_count))
output
{'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}

Note defaultdict auto-creates missing keys using the factory function. Common factories: int (0), list ([]), set (set()).

Counter

syntax
from collections import Counter
example
from collections import Counter

letters = Counter("mississippi")
print(letters.most_common(3))

inventory = Counter(apples=5, oranges=3)
inventory.update(apples=2)
print(inventory["apples"])
output
[('s', 4), ('i', 4), ('p', 2)]
7

Note Counter supports arithmetic: Counter('aab') - Counter('ab') gives Counter({'a': 1}). most_common() returns elements in descending frequency.