# Dictionary Comprehension in Python

Filed Under: Python

This article briefly covers the dictionary comprehension in Python. A Python dictionary is a very useful feature of Python Language. It serves as a mapping between keys to their values.

Sometimes, assigning values to specific keys might get too tedious for a programmer. Therefore Python has a provision of Dictionary Comprehension to save user’s precious time.

## Basic Python Dictionary Comprehension

```# Dictionary stores 1 for odd keys, 0 for even keys
odd = {key: key % 2 for key in range(1, 10)}

# Printing the dictionary
print(odd)
```

Output:

```{1: 1, 2: 0, 3: 1, 4: 0, 5: 1, 6: 0, 7: 1, 8: 0, 9: 1}
```

There are a few elements involved in as single line of code. Let us walk through each one of them.

• Variable`odd` – The dictionary variable that stores all the information.
• Key`key` – The keys for the dictionary.
• Value`key % 2` – The values corresponding to the keys.
• Iterator`for key` – The job of the iterator is to store relevant value for each iteration.
• Iterable`range(1, 10)` – The iterable is responsible for the functioning of the loop and granting value to the iterator.

## Some illustrative examples

There is a need to go through more examples, to become capable of using dictionary comprehension in day-to-day coding.

### Convert Temperature

```# Temperatures in Celcius
celcius = {"Mumbai":36.5, "Delhi":27.6, "Bangalore":32.1, "Dholakpur":40.4}

# Temperature in Fahrenheit
fahrenheit = {key: value*(9/5) + 32 for key,value in celcius.items()}

# Printing the temperatures
print(fahrenheit)
```

Output:

```{'Mumbai': 97.7, 'Delhi': 81.68, 'Bangalore': 89.78, 'Dholakpur': 104.72}
```

In the above example, the dictionary comprehension goes through the items of another dictionary and assigns key and value pairs according to the formula designed.

### Presence of elements

```# A list of integers
lis = [2, 5, 6, 12, 9, 7]

# A dictionary for look-up if element is present in list
present = {key: 1 for key in lis}

# Printing the Dictionary
print(present)
```

Output:

```{2: 1, 5: 1, 6: 1, 12: 1, 9: 1, 7: 1}
```

This conversion of list to a dictionary reduces the time complexity for any look-up queries. The check for the presence of elements can be done in `O(1)` complexity instead of `O(N)`.

### Inverting a Dictionary

```# A dictionary containing numbers in integers and strings
numbers = {1: "one", 2: "two", 3:"three", 4: "four", 5: "five"}

# Inverting a Python dictionary
invert_numbers = {value: key for key, value in numbers.items()}

# Printing the inverted dictionary
print(invert_numbers)
```

Output:

```{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
```

One of the most useful implementation of dictionary comprehension is inverting a Python dictionary. The above code switches the key and value pairs.

## Conditional Dictionary Comprehension

There is yet another element that can be added to the dictionary comprehension – Conditional Statement. These statements can be used to filter dictionary contents according to keys or values.

```# Temperatures
temp = {"Mumbai":36.5, "Delhi":27.6, "Bangalore":32.1, "Dholakpur":40.4}

# Places with high temperature
hot = {key: value for key, value in temp.items() if value >= 35}

# Places with low temperatures
cold = {key: value for key, value in temp.items() if value < 35}

# Printing the dictionaries
print("Hot places =", hot)
print("Cold places =", cold)
```

Output:

```Hot places = {'Mumbai': 36.5, 'Dholakpur': 40.4}
Cold places = {'Delhi': 27.6, 'Bangalore': 32.1}
```

The conditional statements are placed after the iteration part if the set of values and keys are fixed in the dictionary made by dictionary comprehension.

In case, there is an if-else condition related to the values of the dictionary, then the conditions must be placed before the iteration segment.

```# Temperatures
temp = {"Mumbai":36.5, "Delhi":27.6, "Bangalore":32.1, "Dholakpur":40.4}

# Places with their type of temperature
hot_or_cold = {key: ('hot' if value >= 35 else 'cold') for key, value in temp.items()}

# Printing the dictionary
print("Hot places =", hot_or_cold)
```

Output:

```Hot places = {'Mumbai': 'hot', 'Delhi': 'cold', 'Bangalore': 'cold', 'Dholakpur': 'hot'}
```

### Multiple conditional statements

```# Temperatures
temp = {"Mumbai":36.5, "Delhi":27.6, "Bangalore":32.1, "Dholakpur":40.4}

# Hot places starting with M
hot_M = {key: value for key, value in temp.items() if value >= 35 if key.startswith('M')}

# Printing the dictionary
print(hot_M)
```

Output:

```{'Mumbai': 36.5}
```

In the above code snippet, there are two filters present, one filters hot places, while the other one filters places that start with `'M'`.

## Nested dictionary comprehension

There can be complex dictionaries enacted by nesting multiple dictionary comprehensions.

### Creating multiplication tables

```# Importing the pretty print library
import pprint

# Creating multiplication tables
tables = {key1:{key2: key1*key2 for key2 in range(1, 10)} for key1 in range(1, 10)}

# Printing the multiplication tables
pprint.pprint(tables)
print()

# Fetch multiplication values
print("5 x 7 =", tables[5][7])
print("3 x 6 =", tables[3][6])
print("8 x 9 =", tables[9][8])
```

Output:

```{1: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9},
2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18},
3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15, 6: 18, 7: 21, 8: 24, 9: 27},
4: {1: 4, 2: 8, 3: 12, 4: 16, 5: 20, 6: 24, 7: 28, 8: 32, 9: 36},
5: {1: 5, 2: 10, 3: 15, 4: 20, 5: 25, 6: 30, 7: 35, 8: 40, 9: 45},
6: {1: 6, 2: 12, 3: 18, 4: 24, 5: 30, 6: 36, 7: 42, 8: 48, 9: 54},
7: {1: 7, 2: 14, 3: 21, 4: 28, 5: 35, 6: 42, 7: 49, 8: 56, 9: 63},
8: {1: 8, 2: 16, 3: 24, 4: 32, 5: 40, 6: 48, 7: 56, 8: 64, 9: 72},
9: {1: 9, 2: 18, 3: 27, 4: 36, 5: 45, 6: 54, 7: 63, 8: 72, 9: 81}}

5 x 7 = 35
3 x 6 = 18
8 x 9 = 72
```

Nested Dictionary Comprehensions lack readability and therefore should be avoided in Python.

## Conclusion

Dictionary Comprehension in Python is a great way to reduce the size of the program, but it may be lead to confusion during code-review. Therefore it is up to your discretion to take home the knowledge imparted by this article.