作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个返回字典的函数:
def to_dict(self):
return dict({'identification': self.identifier,
'information': self.information,
'nodes': {e.position: e.to_dict for e in self.children}
})
有没有办法选择性地添加每个 k/v?这不起作用,例如:
def to_dict(self):
return dict({'identification': self.identifier,
'information': self.information,
'nodes': {e.position: e.to_dict for e in self.children} if self.children
})
有没有一种方法可以添加字典创建的可选部分,而不必为每个变体构建一个单独的字典?有没有更好的方法来做到这一点?
最佳答案
在本地存储字典,在返回之前用你的额外信息更新它:
def to_dict(self):
retval = {'identification': self.identifier,
'information': self.information,
}
if self.children:
retval['nodes'] = {e.position: e.to_dict for e in self.children}
return retval
我在示例中删除了 dict()
构造函数,它完全是多余的。但是因为您所有的键也是有效的 Python 标识符,您可以通过使用 dict()
构造函数和关键字参数以稍微更紧凑的方式定义您的字典:
def to_dict(self):
retval = dict(identification=self.identifier,
information=self.information)
if self.children:
retval['nodes'] = {e.position: e.to_dict for e in self.children}
return retval
关于python - 字典创建中的可选字典项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12641029/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!