Python dictionary comprehension

In this Python tutorial, we will discuss Python dictionary comprehension. Here we will also cover the below examples:

  • Python dictionary comprehension if else
  • Python dictionary comprehension multiple keys
  • Python dictionary comprehension example
  • Python dictionary comprehension from list
  • Python dictionary comprehension duplicate keys
  • Python dictionary comprehension filter
  • Python dictionary comprehension append
  • Python dict comprehension add key
  • Python dict comprehension with default dict

Python dictionary comprehension

  • In Python, to convert one dictionary into another we can use the dictionary comprehension method. This method is a short way to create a dictionary.
  • To perform this particular task we have to access the key-value pair object of a dictionary.
  • Let’s see how to use the dictionary comprehension method in Python. To do this task you will need some dictionary methods like items() keys() and values().

Example:

dic_key = ['m','u','t','z','x']
dic_val = [19,67,28,17,15]  
new_dic = { a:b for (a,b) in zip(dic_key, dic_val)} 
  
print (new_dic)

In the above code, we have declared a list that is ‘dic_key’ and it contains only keys elements similar to the case of the ‘dic_val’ list that contains only values. Now create a variable and show a dictionary comprehension method.

Output:

Python dictionary comprehension
Python dictionary comprehension

This is how to check the dictionary comprehension method in Python

Another way to solve the dictionary comprehension method in Python

Here we can see how we can use dictionary comprehension using a key-value pair from another dictionary.

Source code:

student_name = {'charles': 47, 'Nathan': 28, 'Adam': 19}

add_value = 92
new_dict = {item: new_value*add_value for (item, new_value) in student_name.items()}
print("New dictionary is:",new_dict)

In the above code, you can see that we have to change the actual value of the original dictionary using a dictionary comprehension method. In this example, we have to update our value by using the ‘*’ operator.

Here is the Screenshot of the following given code

Python dictionary comprehension method
Python dictionary comprehension method

Read: Python dictionary find a key by value

Python dictionary comprehension if else

  • Here we can see how to use the if-else condition in the dictionary comprehension method.
  • In this case, a new original dictionary is initialized via dictionary comprehension.
  • In Python, the if-else statement is used to evaluate whether a condition is true or false. If the expression is true the ‘if’ statement executes otherwise the ‘else’ statement executes. If a condition is true then ‘else’ statement will execute.

Check out the following source code:

your_dict = {'new_key': {'m', 'u', 't'}, 'k2_new': {'John', 'George'}, 'k3_new': {'Smith', 'Denver'}}

dict_comp = {"u is contain in {}".format(n_key) if 'u' in n_val else "u not contain in {}".format(n_key): n_val for n_key, n_val in your_dict.items()}
print(dict_comp)

In this example first, we will initialize a dictionary and assign them key-value pair elements. Now we have to use an if-else statement to evaluate whether the key contains ‘u’ or not. If the ‘u’ variable is stored in a given dictionary then the condition is true else it will display the ‘u’ is not contained in the dictionary.

Execution:

Python dictionary comprehension if else
Python dictionary comprehension if else

This is how to check if else condition in the dictionary comprehension method

Another way to check how to use the if-else condition in dictionary comprehension.

Example:

my_dict = {"a":34,"v":16,"x":19,"l":20}

b = {x:('even no' if y%2==0 else 'odd no') for (x,y) in my_dict.items()}
print(b)

In this example, we can check if the value of the dictionary is an even number then the condition is true ‘else’ the condition is false.

Here is the implementation of the following given code

Python dictionary comprehension if else method
Python dictionary comprehension if-else method

Read: Python convert dictionary to list

Python dictionary comprehension multiple keys

  • Here we can check how to use multiple keys in a dictionary via the dictionary comprehension method.
  • To do this particular task we can use the np.zeroes function. This function returns a new shape and multiple key-value pair elements with zeros.

Example:

import numpy as np
new_key=['a','z','y']
you_dict={a_key:np.zeros(2) for a_key in new_key}
print(you_dict)

Here is the Screenshot of the following given code

Python dictionary comprehension multiple keys
Python dictionary comprehension multiple keys

This is how to use multiple keys in dictionary comprehension.

Read: Python dictionary remove

Python dictionary comprehension example

  • let us take an example and check how to use a dictionary comprehension method in Python.

Example:

Here let us use a range of numbers and create an empty dictionary. Now check the condition if variable ‘p’ is divisible by 3 then the number will get multiplied by 4.

new_num = range(21)
new_dict_for = {}

for p in new_num:
    if p%3==0:
        new_dict_for[p] = p**4

print(new_dict_for)

Here is the output of the following given code

Python dictionary comprehension example
Python dictionary comprehension example

Read: Python dictionary length

Python dictionary comprehension from list

  • Here we can see how to use a list in a dictionary comprehension method.
  • To do this task, suppose we have a list of names and we can use the dictionary comprehension method to initialize a dictionary with names. In this example, we have to check the length of each string which is available in the dictionary and it will display as the value.

Example:

dictionary = ['John', 'George', 'Micheal','Potter']

b = {m:len(m) for m in dictionary}

print(b)

Here is the Screenshot of the following given code

Python dictionary comprehension from list
Python dictionary comprehension from list

Read: Python Dictionary index

Python dictionary comprehension duplicate keys

  • Let us see how to check if duplicate keys are present in the dictionary by using the dictionary comprehension method.
  • For this problem, we can use itertool.chain() method. This function always returns an iterable series and comes under the category of iterators.

Example:

from itertools import chain

to_dictionary = {'m':9, 'o':7, 'g':7, 'h':6}
new_re_dict = {}
for k, v in to_dictionary.items():
	new_re_dict.setdefault(v, set()).add(k)
output = set(chain.from_iterable(
		new_val for k, new_val in new_re_dict.items()
		if len(new_val) > 1))

print("duplicate keys:",output)

Here is the Execution of the following given code

Python dictionary comprehension duplicate keys
Python dictionary comprehension duplicate keys

This is how to check duplicate keys is present in the dictionary or not

Another example to check how to find duplicate keys in Python using dictionary comprehension method

Example:

you_dictionary = {"George":12, "Micheal":19, "Micheal":15}

ne_dic = {}
for new_key, new_val in you_dictionary.items():
    ne_dic[new_val] = new_key
print(ne_dic)

In the above code, we have used dict.items() method to remove duplicate keys from a dictionary. In this example, the value pair is compared to the key element if there is a duplicate key in the dictionary then it will check the condition dic[new_val]== new_key and display the result.

Here is the Screenshot of the following given code

Python dictionary comprehension duplicate keys method
Python dictionary comprehension duplicate keys method

Read: Python dictionary initialize

Python dictionary comprehension filter

  • Here we can see how to use the filter method in a dictionary.
  • In Python, the filter() is a built-in function and it takes an iterable sequence that returns a filter object.
  • In this example, the ‘fo_ne_dict’ variable contains filtered elements from the dictionary that means whose keys are divisible by 3.

Source Code:

my_dict = {9:"Richard",97:"Joseph",84:"Thomas",72:"Franco",6:"Apollo"}
fo_ne_dict = dict()

for (new_k, new_v) in my_dict.items():

   if new_k % 3 == 0:
       fo_ne_dict[new_k] = new_v
print('Dictionary comprehension filter:',fo_ne_dict)

Here is the implementation of the following given code

Python dictionary comprehension filter
Python dictionary comprehension filter

This is how to use filter() method in dictionary comprehension method

Python dictionary comprehension append

  • To append the elements in the dictionary we can easily use the method append() to add elements to the keys or values in the dictionary.
  • To do this particular task suppose we have a dictionary whose keys in the dictionary are “stu_name” and “stu_address”. By using the append() method we can calculate the values for the keys and display the result in the form of key-value pairs.

Code:

student_dict = {"stu_name":[],"stu_address":[]};

new_dict = {"country":[],"City":[]};
student_dict["stu_name"].append("JOhn")
new_dict["country"].append("australia")
print(student_dict)
print(new_dict)

Execution:

Python dictionary comprehension append
Python dictionary comprehension append

This is how to use the append() method in a dictionary comprehension

Read: Python dictionary filter

Python dict comprehension add key

  • Let us see how to add key elements to the dictionary via the dictionary comprehension method.
  • In this example we can easily use the ** operator to add the elements in the dictionary. This is a mathematical operation that helps the user to add elements in a specific key.

Example:

new_lis = [{'m': 'd'}, {'e': 'g'}, {'j': 'l'}]
new_out = [dict(item, **{'add_z':'add_y'}) for item in new_lis]

print("Add key",new_out)

Here is the implementation of the following given code

Python dict comprehension add key
Python dict comprehension add key

This is how to add key elements in a dictionary comprehension

Read: Python Dictionary sort

Python dict comprehension with default dict

This method always returns a dictionary-like object. In Python, the default dict method never raises a key error. In this example first, you have to import a default dict from the collections and initialize a default dict and pass the list to the default factory.

Example:

from collections import defaultdict
  
you_dict = defaultdict(list)
for x in range(6):
    you_dict[x].append(x)
      
print("Add values and keys:",you_dict)

Here is the output of the following given code

Python dict comprehension with default dict
Python dict comprehension with default dict

You may also like reading the following articles related to the dictionary.

In this Python tutorial, we have discussed Python dictionary comprehension. Here we will also cover the below examples:

  • Python dictionary comprehension if else
  • Python dictionary comprehension multiple keys
  • Python dictionary comprehension example
  • Python dictionary comprehension from list
  • Python dictionary comprehension duplicate keys
  • Python dictionary comprehension filter
  • Python dictionary comprehension append
  • Python dict comprehension add key
  • Python dict comprehension with default dict