Python Snippet

Python Dict Comprehension Cheat Sheet

Difficulty: Easy

Dict comprehensions build mappings without explicit loops, the same way list comprehensions build lists. They are the right tool for inverting a dict, projecting a list of tuples into a key-value map, and filtering an existing dict by predicate. This snippet covers the basic build form, the invert and merge patterns, and the filtering form for trimming an existing dict.

Code Snippets
/

Python Dict Comprehension Cheat Sheet

Python Dict Comprehension Cheat Sheet

Dict comprehensions build mappings without explicit loops, the same way list comprehensions build lists. They are the right tool for inverting a dict, projecting a list of tuples into a key-value map, and filtering an existing dict by predicate. This snippet covers the basic build form, the invert and merge patterns, and the filtering form for trimming an existing dict.

Python
Easy
3 snippets
py-comprehensions
py-list-comprehensions
code-template
cheat-sheet

1,133 views

15

Dict comprehensions use {key: value for ... in iterable}. The most common shape is computing a key from each element and a value from a function of that element, which collapses a five-line for / dict[key] = value loop into one expression. Building from a list of tuples is identical to dict(rows), but the comprehension form is more flexible because it lets you transform the keys and values inline. Time complexity is O(n) for n input elements.