I have a function returning a dictionary:
def to_dict(self):
return dict({'identification': self.identifier,
'information': self.information,
'nodes': {e.position: e.to_dict for e in self.children}
})
Is there a way to optionally add each k/v? This does not work e.g:
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
})
Is there a way to add in optional parts of dict creation without having to build a separate dictionary for each variation; is there a better way to do this even ?
Store the dict locally, update it with your extra info before returning:
I removed the
dict()constructor in my example, it is entirely redundant. But because all your keys are also valid python identifiers, you could define your dict in a slightly more compact manner by using thedict()constructor and keyword arguments: