Dict comprehension

2 snippets in Python

PYPython

Dictionary Comprehensions

PY · Dictionaries
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.

Dict Comprehensions (Detailed)

PY · Comprehensions & Generators
syntax
{key_expr: val_expr for item in iterable if cond}
example
# Invert a dictionary
http_codes = {200: "OK", 404: "Not Found", 500: "Server Error"}
code_lookup = {msg: code for code, msg in http_codes.items()}
print(code_lookup["Not Found"])

# From two parallel lists
keys = ["host", "port", "debug"]
vals = ["localhost", 8080, True]
config = {k: v for k, v in zip(keys, vals)}
print(config)
output
404
{'host': 'localhost', 'port': 8080, 'debug': True}

Note When inverting a dict, duplicate values in the original will cause key collisions; the last one wins.