Python 字典推导式中的条件表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18246827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:17:19  来源:igfitidea点击:

Conditional expressions in Python Dictionary comprehensions

pythondictionary-comprehension

提问by user462455

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

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

采纳答案by Rohit Jain

Move the ifat the end:

移动if最后:

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 dictfactory over a generator expression):

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

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

回答by falsetru

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.

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