Python Dictionary Comprehension

In Python, a comprehension stands as an elegantly succinct technique to construct complex data structures via the utilization of iterators. Specifically, a dictionary comprehension represents a streamlined approach to fashioning a fresh dictionary in Python. This construct mirrors the concept of list comprehension, yet diverges by crafting a dictionary instead of a list, thus contributing to the code's conciseness and readability while adeptly managing data transformation.

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

Presented below is an alternative implementation that accomplishes the intended outcome without resorting to the utilization of Dictionary Comprehension. However, this approach necessitates the inclusion of a more extensive code segment. The adoption of Dictionary Comprehension not only obviates the need for an extended code base but also contributes to sustaining the pristine clarity and organization of your code. This demonstrates the inherent advantage of employing Dictionary Comprehension as it efficiently optimizes code length while preserving its overall legibility.

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.

Conclusion

Python Dictionary Comprehension is a concise and efficient method to create dictionaries in Python by specifying key-value pairs within a compact syntax. It offers a streamlined alternative to traditional methods, allowing developers to create dictionaries with less code and improved readability. By using dictionary comprehension, you can construct dictionaries with ease while maintaining code clarity and conciseness.