Conditional expressions in Python Dictionary comprehensions

user462455 picture user462455 · Aug 15, 2013 · Viewed 29.5k times · Source
a = {"hello" : "world", "cat":"bat"}

# Trying to achieve this
# Form a new dictionary only with keys with "hello" and their values
b = {"hello" : "world"}

# This didn't work

b = dict( (key, value) if key == "hello" for (key, value) in a.items())

Any suggestions on how to include a conditional expression in dictionary comprehension to decide if key, value tuple should be included in the new dictionary

Answer

Rohit Jain picture Rohit Jain · Aug 15, 2013

Move the if at the end:

b = dict( (key, value) for (key, value) in a.items() if key == "hello" )

You can even use dict-comprehension (dict(...) is not one, you are just using the dict factory over a generator expression):

b = { key: value for key, value in a.items() if key == "hello" }