• Skip to secondary menu
  • Skip to main content
  • Skip to primary sidebar

Python and R Tips

Learn Data Science with Python and R

  • Home
  • Python
  • Pandas
    • Pandas 101
  • tidyverse
    • tidyverse 101
  • R
  • Linux
  • Conferences
  • Python Books
  • About
    • Privacy Policy
You are here: Home / Python / dict comprehension / 5 Examples Using Dict Comprehension in Python

5 Examples Using Dict Comprehension in Python

January 23, 2018 by cmdlinetips

List Comprehension is a handy and faster way to create lists in Python in just a single line of code. It helps us write easy to read for loops in a single line.

In Python, dictionary is a data structure to store data such that each element of the stored data is associated with a key. Dictionary data structure lets you query the data using key very efficiently.

The idea of comprehension is not just unique to lists in Python. Dictionaries, one of the commonly used data structures in data science, can also do comprehension. With dict comprehension or dictionary comprehension, one can easily create dictionaries.

Remember that, in python a list is defined with square brackets [] and a dictionary is defined with curly braces {}. The idea used in list comprehension is carried over in defining dict comprehension as well. Dict comprehension is defined with a similar syntax, but with a key:value pair in expression.

  • {key:value for i in list}

Let us see 5 simple examples of using Dict Comprehension to create new dictionaries easily.

[update:] Added sixth example of dict comprehension to delete keys in a dictionary.

Dict Comprehension Example 1

Let us see a quick example of creating a dict comprehension from a list of numbers.

Here let us use a list of numbers and create a dictionary with string value of the number as key and the number as values.

# dict comprehension to create dict with numbers as values
>{str(i):i for i in [1,2,3,4,5]}
{'1': 1, '3': 3, '2': 2, '5': 5, '4': 4}

Dict Comprehension Example 2

Let us say, we have a list of fruits and we can use dict comprehension to create a dictionary with fruits, the list elements as the keys and the length of each string as the values.

# create list of fruits
>fruits = ['apple', 'mango', 'banana','cherry']
# dict comprehension to create dict with fruit name as keys
>{f:len(f) for f in fruits}
{'cherry': 6, 'mango': 5, 'apple': 5, 'banana': 6}

Dict Comprehension Example 3

Let us create a dictionary with dict comprehension such that elements of the list as the keys and the elements with first letter capitalized as the values.

>{f:f.capitalize() for f in fruits}
{'cherry': 'Cherry', 'mango': 'Mango', 'apple': 'Apple', 'banana': 'Banana'}

Dict Comprehension Example 4

Let us use enumerate function in dictionary comprehension. If you have not used enumerate: enumerate can take any thing iterable as input and returns element and its index.

Here we use enumerate function on the list to create index and list element tuples and use them to create a dictionary with dict comprehension. We create a dictionary with elements of the list as the keys and the index of elements as the values. Such dictionaries with element index are often useful in a variety of scenarios.

# dict comprehension example using enumerate function
>{f:i for i,f in enumerate(fruits)}
{'cherry': 3, 'mango': 1, 'apple': 0, 'banana': 2}

Dict Comprehension Example 5

Another use of dict comprehension is to reverse key:value in an existing dictionary. Sometimes you may want to create new dictionary from an existing directory, such that the role of key:value pair in the first dictionary is reversed in the new dictionary. We can use Dict Comprehension and flip the element to index dictionary to index to element dictionary.

# dict comprehension example to reverse key:value pair in a dictionary
>f_dict = {f:i for i,f in enumerate(fruits)}
>f_dict
{'apple': 0, 'banana': 2, 'cherry': 3, 'mango': 1}
# dict comprehension to reverse key:value pair in a dictionary
>{v:k for k,v in f_dict.items()}
{0: 'apple', 1: 'mango', 2: 'banana', 3: 'cherry'}

We have used dictionaries’ items function to get key, value pairs in an existing dictionary and created a new dictionary where the keys in the original dictionary are values in new dictionary and vice versa.


Dict Comprehension Example 6: How To Delete Selected Keys from Dictionary using Dict Comprehension?

Let us say you have dictionary and want to create a new dictionary by removing certain key-value pair. We can use Dict Comprehension to remove selected key-value pairs from a dictionary and create a new dictionary.

Let us use the “fruit” dictionary we created above.

fruits = ['apple', 'mango', 'banana','cherry']
f_d1 ={f:f.capitalize() for f in fruits}
f_d1

Let us use diction comprehension to remove two keys, apple and banana, and their values from the fruit dictionary.

# keys to be removed
>remove_this = {'apple','cherry'}
# dict comprehension example to delete key:value pairs in a dictionary
>{key:f_d1[key] for key in f_d1.keys() - remove_this}
{'banana': 'Banana', 'mango': 'Mango'}

We have removed the keys, apple and cherry, by simply using dict keys object with set operations and now the new dictionary contains just banana and mango.

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Related posts:

Default Thumbnail5 Examples of Using List Comprehensions in Python Default ThumbnailGetting Started With Python Dictionaries: Python Tips Default ThumbnailMastering Lists in Python Using List Comprehensions Default ThumbnailHow To Add a New Column Using a Dictionary in Pandas Data Frame ?

Filed Under: dict comprehension, Dictionary comprehension, Python Tips Tagged With: dict comprehension, Dictionary comprehension, List Comprehension, Python Tips

Primary Sidebar

Subscribe to Python and R Tips and Learn Data Science

Learn Pandas in Python and Tidyverse in R

Tags

Altair Basic NumPy Book Review Data Science Data Science Books Data Science Resources Data Science Roundup Data Visualization Dimensionality Reduction Dropbox Dropbox Free Space Dropbox Tips Emacs Emacs Tips ggplot2 Linux Commands Linux Tips Mac Os X Tips Maximum Likelihood Estimation in R MLE in R NumPy Pandas Pandas 101 Pandas Dataframe Pandas Data Frame pandas groupby() Pandas select columns Pandas select_dtypes Python Python 3 Python Boxplot Python Tips R rstats R Tips Seaborn Seaborn Boxplot Seaborn Catplot Shell Scripting Sparse Matrix in Python tidy evaluation tidyverse tidyverse 101 Vim Vim Tips

RSS RSS

  • How to convert row names to a column in Pandas
  • How to resize an image with PyTorch
  • Fashion-MNIST data from PyTorch
  • Pandas case_when() with multiple examples
  • An Introduction to Statistical Learning: with Applications in Python Is Here
  • 10 Tips to customize ggplot2 title text
  • 8 Plot types with Matplotlib in Python
  • PCA on S&P 500 Stock Return Data
  • Linear Regression with Matrix Decomposition Methods
  • Numpy’s random choice() function

Copyright © 2025 · Lifestyle Pro on Genesis Framework · WordPress · Log in

Go to mobile version