python - Unpack a list of dictionaries and set each to its own variable -
so creating class arguments, takes 1 or more dictionaries. intializes list of dictionaries. defining __add__()
method takes 2 objects of class , returns new object consisting of dictionaries first object followed of second object.
class dictlist: def __init__(self, *d): self.dl = [] argument in d: if type(argument) != dict: raise assertionerror(str(argument) + ' not dictionary') if len(argument) == 0: raise assertionerror('dictionary empty') else: self.dl.append(argument)
for example,
d1 = dictlist(dict(a=1,b=2), dict(b=12,c=13)) d2 = dictlist(dict(a='one',b='two'), dict(b='twelve',c='thirteen'))
then d1+d2 equivalent to
dictlist({'a': 1, 'b': 2}, {'b': 12, 'c': 13}, {'a': 'one', 'b': 'two'}, {'b': 'twelve', 'c': 'thirteen'})
to add 2 lists together, use +
operator.
and create 1 of objects out of list of dicts instead of bunch of separate dict arguments, use *
unpack list.
so:
def __add__(self, other): return type(self)(*(self.dl + other.dl))
Comments
Post a Comment