{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)
# 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 inzip(keys, vals)}print(config)
Note When inverting a dict, duplicate values in the original will cause key collisions; the last one wins.
Frequently asked questions
How does Python handle dict comprehension?
Python covers this with 2 copy-ready snippets on this page. The "Dictionary Comprehensions" snippet in Python uses `{key_expr: val_expr for item in iterable if condition}`.
Which code does the Python example use?
The "Dictionary Comprehensions" snippet uses `{key_expr: val_expr for item in iterable if condition}`, from the Dictionaries section of the Python cheat sheet.
What other Python snippets are shown for "dict comprehension"?
Besides "Dictionary Comprehensions", this page also shows "Dict Comprehensions (Detailed)".
Is there anything to watch out for?
Yes. For "Dictionary Comprehensions": Dict comprehensions are great for transforming or filtering dictionaries in a single expression.