Python Dictionary Comprehension

In Python, a comprehension is a compact way of creating a data structure from iterators. Dictionary comprehension is a concise way to create a new dictionary in Python. It is similar to list comprehension, but creates a dictionary instead of a list. Syntax:
{key: value for (key, value) in iterable}
For example, to create a dictionary that maps integers to their squares, you can use the following dictionary comprehension:
dct = {i: i*i for i in range(5)} print(dct)
//Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
This creates a dictionary with keys from 0 to 5 and values as their square.

Without Dictionary Comprehension

Here is the code without Dictionary Comprehension to achieve the above result. But you should write more lines of code. So, Dictionary Comprehension saves you having to write several lines of code, and keeps the readability of your code neat.
dct = dict() for n in range(0, 5): dct[n] = n*n print(dct)
//Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Dictionary Comprehension | Example

A simple dictionary comprehension that uses string as an iterable.
dct = {q.upper(): q*2 for q in 'Python'} print (dct)
//Output: {'P': 'PP', 'Y': 'yy', 'T': 'tt', 'H': 'hh', 'O': 'oo', 'N': 'nn'}

Dictionary Comprehension from two iterables


Python dictionary comprehension
Here there are two lists named keys and value and iterating over them with the help of zip() function.
keys = [1,2,3,4] values = ['East','West','North','South'] dct = { k:v for (k,v) in zip(keys, values)} print (dct)
//Output: {1: 'East', 2: 'West', 3: 'North', 4: 'South'}

Dictionary comprehension | Enumerate

By using enumerate() method, you can create a dictionary from the list with list index number as key and list element as value.
values = ['East','West','North','South'] dct = {k:v for k,v in enumerate(values)} print(dct)
//Output: {0: 'East', 1: 'West', 2: 'North', 3: 'South'}

Dictionary comprehension | if clause

Dictionary comprehension can also include an optional if clause, like this:
dct = {i: i*i for i in range(10) if i % 2 == 0} print(dct)
//Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
This creates a dictionary with only even keys and their square values.

Dictionary comprehension | Extracting a subset

If you want to select some items from Dictionary, you can use Dictionary comprehension to extract particular keys and values from a dictionary.
colors = {0: 'Red', 1: 'Green', 2: 'Blue', 3: 'Yellow', 4: 'Orange', 5: 'Violet'} selectedColors = [1, 3, 5] dct = {k: colors[k] for k in selectedColors} print(dct)
//Output: {1: 'Green', 3: 'Yellow', 5: 'Violet'}

Nested Dictionary Comprehension

Here is an example for nested Dictionary Comprehension.
dct = {(key,value): key+value for key in range(2) for value in range(2)} print(dct)
//Output: {(0, 0): 0, (0, 1): 1, (1, 0): 1, (1, 1): 2}

Dictionary Comprehension | Advantages

  1. They are easy to read and understand, as the syntax is similar to list comprehensions and follows a clear, logical structure.
  2. They can be used to perform complex operations on dictionaries, such as filtering, mapping, and aggregating items, in a single line of code.
  3. They can be more memory-efficient than using for loops, as the items are generated on the fly, rather than being stored in a separate list or variable.
  4. They can be faster than using for loops, as the operations are applied directly to the items, rather than iterating over them multiple times.

Dictionary Comprehension | Disadvntages

  1. They may be less readable or more difficult to understand for people who are not familiar with the syntax.
  2. They can be less flexible than using for loops, as they are limited to a single expression and do not allow for multiple statements or control flow.
  3. They may be less efficient for very large dictionaries or when dealing with complex operations that cannot be expressed in a single expression.
  4. They can be less explicit and harder to debug when the code fails.
  5. They can be less explicit when you are trying to filter the dictionary based on multiple conditions.