Conditional expressions in Python Dictionary comprehensions

半世苍凉 提交于 2019-11-30 07:18:34

Move the if at the end:

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!