Python Dictionary With Examples

Python dictionary comprehension is used to create dictionaries using iterable. A dictionary is a collection that is unordered, mutable, and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with {} and key:value pair separated by commas. The dictionaries are indexed by keys.

The values can be of any type of object and can be allowed duplicates, keys must be of an immutable type such as string, numbers(int, float), tuple and it cannot be allowed duplicates, in case you add the duplicates, which will be updated the existing keys of the dictionary.

In this article, I will explain Python dictionary comprehension with examples and use this how to create a dictionary concisely and elegantly.

Quick Examples of Python Dictionary Comprehension

Following are quick examples of dictionary comprehension.


# Example 1: Create a dictionary using dictionary comprehension 
my_dict={n:n*n for n in range(10)if n%2!=0}

# Example 2: Convert the numbers squares to cubes by using dict comprehension 
my_squares = {1:1,2:4,3:9,4:16,5:25}
my_cubes = {key: value*key for (key, value) in my_squares.items()}

# Example 3: Using if conditional modify the dictionary
family_id = {'richerd': 44,'mary':7, 'lucy': 40, 'William': 60, 'wick': 10}
voters_id = {key: value for (key, value) in family_id.items()if value >= 18}

# Example 4: Using multiple if conditional modify the dictionary
family_id = {'richerd': 44,'mary':7, 'lucy': 40, 'William': 60, 'wick': 10}
voters_id = {key: value for (key, value) in family_id.items()if value >= 18 if value >= 60}

# Example 5: Using if-else conditional modify the dictionary
family_id = {'richerd': 44,'mary':7, 'lucy': 40, 'William': 60, 'wick': 10}
voter_id = {key: ('eligible 'if value >= 18 else 'not eligible') for (key, value) in family_id.items()}

# Example 6: Create nested dictionary using nested dictionary comprehension
my_dict = {
    key1: {key2: key2**2 for key2 in range(1,6)} for key1 in range(5, 20, 5)
}

# Example 7:  Using enumerate() in dictionary comprehension 
list = ['java', 'python', 'pandas']
my_dict = {key:value for key,value in enumerate(list)}

1. Syntax of Dictionary

Following is the syntax of the Python dictionary.


# Syntax of the dictionary
my_dict={"course":"python","fee":4000,"duration"="30 days"}

2. Syntax of Dictionary Comprehension

Following is the syntax of the comprehension.


# Syntax of the dictionary comprehension
{key: value for variable in iterable(if conditional)}

Comprehension can be used to substitute python for loops. However, not all for loops can write as a dictionary comprehension but all dictionary comprehension can write with a for loop. First, let’s see how we use for loop without dictionary comprehension.


# Create a dictionary
my_dict = {}
for n in range(10):
    if n%2!=0:
        my_dict[n] = n*n
print(my_dict)

# Outputs:
 {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

Using dictionary comprehension we can reduce the above code.


# Create a dictionary using dictionary comprehension 
my_dict={n:n*n for n in range(10)if n%2!=0}
print(my_dict)

# Outputs:
 {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

3. List vs Dictionary Comprehension

Let’s verify the comparison between list comprehension and Python dictionary comprehension.

Python dictionary comprehension is an elegant and concise way to create dictionaries using iterable. Moreover, it is the same as a list comprehension but the only difference is syntax due to the structure of dictionaries.


# Verify the similarity between a list & dictionary comprehension
list = [20,10,40,50]
products = [x*2 for x in list]
print(products)
# Outputs: 
[40, 20, 80, 100]

# Dictionary Comprehensive
divisions ={x:x/5 for x in list}
print(divisions)
# Outputs:
 {20: 4.0, 10: 2.0, 40: 8.0, 50: 10.0}, # Division(/) returns a float value

We have taken an iterable which is a list. In list comprehension, we create a list that contains the products of the list. In dictionary comprehension, we need to specify both keys and values based on the iteration. The returned dictionary contains the elements as keys and their divisions as values.

4. Update Using Dictionary Comprehension

We can access the key-value pairs in a dictionary by using the items() method. It returns a list of tuples(key: value) pairs.

We can use the elements of an existing Python dictionary as iterable in dictionary comprehension. It provides us to create the dictionaries based on existing dictionaries.


# Convert the numbers squares to cubes by using dict comprehension 
my_squares = {1:1,2:4,3:9,4:16,5:25}
my_cubes = {key: value*key for (key, value) in my_squares.items()}
print(my_cubes)

# Outputs:
 {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

In the above example, note that we have converted the numbers in the form of squares to cubes in very short code.

5. Adding Conditional to Python Dictionary Comprehension

We can modify the existing dictionaries by using dictionary comprehension with the help of conditionals.

5.1 If Condition


# Using if conditional modify the dictionary
family_id = {'richerd': 44,'mary':7, 'lucy': 40, 'William': 60, 'wick': 10}
voters_id = {key: value for (key, value) in family_id.items()if value >= 18}
print(voters_id)

# Outputs:
 {'richerd': 44, 'lucy': 40, 'William': 60}

Note that we have filtered voters_id dictionary from family_id dictionary in a single line code using dictionary comprehension with the help of if conditional.

5.2 Multiple if Condition

Here, we have filtered above 60 or equal from the existing dictionary. Remember, that the multiple if statements work as if they had and clauses between them.


# Using multiple if conditional modify the dictionary
family_id = {'richerd': 44,'mary':7, 'lucy': 40, 'William': 60, 'wick': 10}
voters_id = {key: value for (key, value) in family_id.items()if value >= 18 if value >= 60}
print(voters_id)

# Outputs:
 {'William': 60}

5.3 if-else Condition

From the below code, we have modified the existing dictionary using dictionary comprehension. In this case above 18 or equal then eligible otherwise not eligible.


# Using if-else conditional modify the dictionary
family_id = {'richerd': 44,'mary':7, 'lucy': 40, 'William': 60, 'wick': 10}
voter_id = {key: ('eligible 'if value >= 18 else 'not eligible') for (key, value) in family_id.items()}
print(voter_id)

# Outputs:
{'richerd': 'eligible', 'mary': 'not eligible', 'lucy': 'eligible', 'William': 'eligible', 'wick': 'not eligible'}

6. Nested Dictionary Comprehension

While adding one dictionary comprehension to another dictionary comprehension we are going to get a nested dictionary.

Here, the value in the Key: value pair can also be another dictionary comprehension. let’s take an example.


# Python Nested Dictionary Comprehension Syntax
{key:{dictionary comprehension} for variable in iterable}

# Create nested dictionary using nested dictionary comprehension
my_dict = {
    key1: {key2: key2**2 for key2 in range(1,6)} for key1 in range(5, 20, 5)
}
print(my_dict)

# Output:
           {5: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25},
           10: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}, 
           15: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}}

Note that we have got a nested dictionary(that means dictionaries are presented inside another dictionary) by adding one dictionary comprehension to another dictionary comprehension.

The nesting concept always starts the outer loop and then goes to the inner loop.

7. Python Dictionary Comprehension with enumerate()

When you need to convert a list to a dictionary, we need the key: value pairs, by applying enumerate() to the list we can get the index of list items. Indices of a list can be used as keys of the dictionary and list Yields below output act as values of the dictionary.


# Using enumerate() in dictionary comprehension 
list = ['java', 'python', 'pandas']
my_dict = {key:value for key,value in enumerate(list)}
print(my_dict)

Yields below output.


{0: 'java', 1: 'python', 2: 'pandas'}

Conclusion

In this article, I have explained what is Python dictionary comprehension and how can we create dictionaries in the easiest way using iterables. Along with this, I have explained how to modify the dictionaries by adding conditional clauses to dictionary comprehension, how to create a nested dictionary using nested dictionary comprehension, and usage of enumerate() in dictionary comprehension.

Happy learning !!

References

Leave a Reply

You are currently viewing Python Dictionary With Examples