• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Dictionary / Dictionary Comprehension in Python

Dictionary Comprehension in Python

Author: Aditya Raj
Last Updated: May 18, 2021

There may be situations while working with dictionaries in python that we need to create a new dictionary from another dictionary by including some  items from the dictionary based on a condition or we want to create a new dictionary having keys and values following a specific condition. We may do it by manually checking the dictionary items one by one using  a for loop and adding them to the new dictionary. In this tutorial we will see how we can achieve the same result using a concise construct called dictionary comprehension in python.

What is dictionary comprehension?

Just like list comprehension is a way to create lists from other lists, dictionary comprehension is a way to create a python dictionary from another dictionary or from any other iterable. We can create new dictionaries with the same elements from the original dictionary based on conditional statements or we can transform the items in the dictionary according to our need. We can either modify the keys or the values or both key and value of items in the dictionary while creating a new dictionary using dictionary comprehension. 

While creating a dictionary using dictionary comprehension, we have to get a key value pair either from any dictionary or from any other iterable.Syntax for dictionary comprehension can be as follows.

myDict={key:value for var in iterable}

While creating a dictionary from a list or tuple using the elements of list or tuple as keys and values derived from the elements, we can use the following syntax.

myDict={key:value for var in list_name}
myDict={key:value for var in tuple_name}

While creating a dictionary from another dictionary, we can use the following syntax.

myDict={key:value for (key,value) in dict_name.items()}

How to use dictionary comprehension?

We can create a dictionary by using elements from a list. Suppose we want to create a python dictionary with elements of the list as keys and values then we can do it as follows.

myList=[1,2,3,4]
myDict={x:x for x in myList}
print("List is:")
print(myList)
print("Created dictionary is:")
print(myDict)

Output:

List is:
[1, 2, 3, 4]
Created dictionary is:
{1: 1, 2: 2, 3: 3, 4: 4}

In the output, we can see that the created dictionary has keys and values same as that of elements in the given list.

We can also modify the elements of the list before adding them to dictionary while creating a new dictionary. Suppose we want to create a dictionary having elements of the list as keys and their squares as values the we can do it as follows.

myList=[1,2,3,4]
myDict={x:x**2 for x in myList}
print("List is:")
print(myList)
print("Created dictionary is:")
print(myDict)

Output:

List is:
[1, 2, 3, 4]
Created dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}

In the output, we can see that the created dictionary has elements of the list as keys and their squares as values.

We can also selectively use items from lists based on conditions while creating the dictionary. Suppose we want to create a dictionary having elements of the list which are even as keys and their squares as values the we can do it as follows.

myList=[1,2,3,4]
myDict={x:x**2 for x in myList if x%2==0}
print("List is:")
print(myList)
print("Created dictionary is:")
print(myDict)

Output:

List is:
[1, 2, 3, 4]
Created dictionary is:
{2: 4, 4: 16}

In the output, we can see that only those elements of the list which are even numbers has been used as keys in the created dictionary and their squares are the respective values of the keys of the dictionary.

We can also create a dictionary  by using items from another dictionary. For this we can extract key value pairs using items() method from the original dictionary. items() method gives a list of tuples as (key,value) pairs which we can use to create a new dictionary .

For example, we can create a new dictionary exactly as a given dictionary using dictionary comprehension as follows.

myDict={1:1,2:2,3:3,4:4}
print("Original Dictionary is")
print(myDict)
newDict={key:value for (key,value) in myDict.items()}
print("New dictionary is:")
print(newDict)

Output:

Original Dictionary is
{1: 1, 2: 2, 3: 3, 4: 4}
New dictionary is:
{1: 1, 2: 2, 3: 3, 4: 4}

In the output, we can see that the new dictionary is containing the same key value pairs as original dictionary.

We can also modify the dictionary items from the original dictionary before including them to the new dictionary. For example, the following program modifies the values of the items before adding them into new dictionary.


myDict={1:1,2:2,3:3,4:4}
print("Original Dictionary is")
print(myDict)
newDict={key:value**2 for (key,value) in myDict.items()}
print("New dictionary is:")
print(newDict)

Output:

Original Dictionary is
{1: 1, 2: 2, 3: 3, 4: 4}
New dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}

In the output, we can see that the keys of the new dictionary as same as original dictionary but the values of the items in new dictionary as squares of values of the item in the original dictionary.

We can also use conditions to selectively choose items from the older dictionary using conditions  while creating a new dictionary.

For example, the following program filters out the items whose keys are odd numbers and considers only those items to add in new dictionary in which the keys are even numbers. It further squares the values of those items before adding them to new dictionary.

myDict={1:1,2:2,3:3,4:4}
print("Original Dictionary is")
print(myDict)
newDict={key:value**2 for (key,value) in myDict.items() if key%2==0}
print("New dictionary is:")
print(newDict)

Output:

Original Dictionary is
{1: 1, 2: 2, 3: 3, 4: 4}
New dictionary is:
{2: 4, 4: 16}

In the output, we can see that the key value pairs in new dictionary have only even numbers as their keys and their squares as respective values.

Conclusion

In this article, we have seen what dictionary comprehension is and how to use them to create new dictionaries. Dictionary comprehensions can be used to replace for loops while creating dictionaries and make the source code more concise  and increase the readability of the code when complex conditions are not used. In cases when we use complex conditional statements inside dictionary comprehension, it may decrease the readability of the source code. The execution of the code may also slow down and the program will require more memory space. So, while handling complex conditional statements to create dictionaries, it is better to use for loops instead of dictionary comprehensions. Stay tuned for more informative articles.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Dictionary Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us