I've got this code:
def update_amounts(self):
container = {}
a = {'a': self.a_amount} if self.a_mount or self.a_amount is None else {'': ''}
container.update(a)
b = {'b': self.b_amount} if self.b_amount or self.b_amount is None else {'':''}
container.update(b)
c = {'c': self.c_amount} if self.c_amount or self.c_amount is None else {'':''}
container.update(c)
return container
And I wanted to know if its possible to do the dict update more efficient than calling the update function three times?
Thanks in regard!
CodePudding user response:
For Python 3.9 , you can use pipe symbol |
to combine multiple dictionaries
def update_amounts(self):
# container = {}
a = {'a': self.a_amount} if self.a_mount or self.a_amount is None else {'': ''}
# container.update(a)
b = {'b': self.b_amount} if self.b_amount or self.b_amount is None else {'':''}
# container.update(b)
c = {'c': self.c_amount} if self.c_amount or self.c_amount is None else {'':''}
# container.update(c)
container = a|b|c
return container
Or, you can just pass the unpacked values for each of the dictionaries to the update method at last:
def update_amounts(self):
container = {}
.
.
.
container.update(**a, **b, **c)
return container