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

use*_*455 8 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())
Run Code Online (Sandbox Code Playgroud)

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

Roh*_*ain 21

移动if到底:

b = dict( (key, value) for (key, value) in a.items() if key == "hello" )
Run Code Online (Sandbox Code Playgroud)

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

b = { key: value for key, value in a.items() if key == "hello" }
Run Code Online (Sandbox Code Playgroud)

  • @ user462455:`dict((key,value)for ... in ... if ...)`不是字典理解; 它是传递给`dict`的生成器理解,具有相同的效果.较新版本的Python具有真正的字典理解,其语法为`{key:value for ... in ... if ...}`. (4认同)

fal*_*tru 8

您不需要使用字典理解:

>>> a = {"hello" : "world", "cat":"bat"}
>>> b = {"hello": a["hello"]}
>>> b
{'hello': 'world'}
Run Code Online (Sandbox Code Playgroud)

dict(...)不是字典解析.