Home » Learn Python » Containers » Dictionary Comprehensions

Dictionary Comprehensions

You can create sets and dictionaries using comprehensions, just like lists.

With dictionaries you need to use a key:value syntax to specify the keys and values.

numbers = {x:x**2 for x in range(5)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Here the keys are the numbers 0-4 and the values are the squares of those numbers.

Leave a Reply

Blog at WordPress.com.