Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional expressions in Python Dictionary comprehensions

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

like image 674
user462455 Avatar asked Aug 15 '13 05:08

user462455


2 Answers

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" }
like image 167
Rohit Jain Avatar answered Oct 03 '22 22:10

Rohit Jain


You don't need to use dictionary comprehension:

>>> a = {"hello" : "world", "cat":"bat"}
>>> b = {"hello": a["hello"]}
>>> b
{'hello': 'world'}

and dict(...) is not dictionary comprehension.

like image 38
falsetru Avatar answered Oct 03 '22 22:10

falsetru