Skip to content

Python dict comprehension if-else | Example code

  • by

Python dictionary comprehension is a method for transforming one dictionary into a new dictionary. Using an if-else in Python dict comprehension is one of the ways to create a new list. It works as a condition to filter out dictionary elements for a new dictionary.

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

Example dict comprehension if-else in Python

Simple example code adding conditionals to Dictionary comprehension. Replace the value with ‘Even‘ if the value module is zero else replaced it with ‘Odd‘.

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}

# Identify odd and even entries
res = {k: ('Even' if v % 2 == 0 else 'Odd') for (k, v) in dict1.items()}

print(res)

Output:

Python dict comprehension if-else

Do comment if you have any doubts or suggestions on this Python dictionary tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading