11
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

kontulai
  • 876
  • 5
  • 19
user462455
  • 12,838
  • 18
  • 65
  • 96

2 Answers2

28

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" }
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • Worked!! Thanks. But why is the syntax different for dict comprehensions compared to list comprehensions – user462455 Aug 15 '13 at 05:30
  • 4
    @user462455: `dict((key, value) for ... in ... if ...)` is not a dictionary comprehension; it's a generator comprehension passed to `dict`, which has the same effect. Newer versions of Python have real dictionary comprehensions with the syntax `{key: value for ... in ... if ...}`. – icktoofay Aug 15 '13 at 05:31
8

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.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    won't this break if there is no HELLO key in the source dictionary? conditional add? No? – Syed Mauze Rehan Jul 14 '17 at 15:47
  • @SyedMauzeRehan, It will break if there's no `hello` key. You can use this: `b = {"hello": a.get('hello')}` (which will return `{'hello': None}` if there's no `hello` key). Or use `b = {"hello": a["hello"]} if 'hello' in a else {}` if you want to get `{}` in case of missing `hello`. – falsetru Jul 15 '17 at 00:41
  • 1
    @SyedMauzeRehan, My point was "You don't need to iterate the dictionary to get single key-value pair." – falsetru Jul 15 '17 at 00:43