Python字典理解中的条件表达式

时间:2013-08-15 05:28:21

标签: python dictionary-comprehension

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

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

2 个答案:

答案 0 :(得分:20)

最后移动if

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

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

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

答案 1 :(得分:8)

您不需要使用词典理解:

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

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