【问题标题】:optional dictionary items in dict creation字典创建中的可选字典项
【发布时间】:2012-09-20 09:34:16
【问题描述】:

我有一个返回字典的函数:

 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
                      })

有没有一种方法可以添加字典创建的可选部分,而不必为每个变体构建单独的字典;有没有更好的方法来做到这一点?

【问题讨论】:

  • 你的问题不清楚。您所说的“可选”是什么意思?取决于哪个条件?
  • 请注意,使用{'key': 'value', ...} 定义字典就足够了。您不需要在这些上使用 dict() 构造函数;这完全是多余的。

标签: python dictionary key conditional key-value


【解决方案1】:

在本地存储字典,在返回之前用你的额外信息更新它:

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() 构造函数和关键字参数以稍微更紧凑的方式定义您的 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

【讨论】:

  • 简单、清晰的解决方案。如果你有很多潜在的 if 语句,你可以将它们存储在另一个字典中,然后执行 retval.extend({key: value for key, value in potentials.items() if value})。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
  • 2016-07-11
  • 1970-01-01
  • 2017-05-05
  • 2021-06-25
  • 2019-08-07
相关资源
最近更新 更多