10
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())

关于如何在字典理解中包含条件表达式以确定键、值元组是否应包含在新字典中的任何建议

4

2 回答 2

24

移动if到最后:

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

您甚至可以使用dict-comprehensiondict(...)不是一个,您只是dict在生成器表达式上使用工厂):

b = { key: value for key, value in a.items() if key == "hello" }
于 2013-08-15T05:28:55.050 回答
8

您不需要使用字典理解:

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

并且dict(...)不是字典理解。

于 2013-08-15T05:29:38.030 回答