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)
您不需要使用字典理解:
>>> a = {"hello" : "world", "cat":"bat"}
>>> b = {"hello": a["hello"]}
>>> b
{'hello': 'world'}
Run Code Online (Sandbox Code Playgroud)
而dict(...)
不是字典解析.
归档时间: |
|
查看次数: |
21080 次 |
最近记录: |