Reputation: 313
So I am creating a class which as arguments, takes 1 or more dictionaries. It then intializes a list of those dictionaries. I am defining an __add__()
method that takes two objects of this class and returns a new object consisting of the dictionaries from the first object followed by those of the second object.
class DictList:
def __init__(self, *d):
self.dl = []
for argument in d:
if type(argument) != dict:
raise AssertionError(str(argument) + ' is not a dictionary')
if len(argument) == 0:
raise AssertionError('Dictionary is 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 would be equivalent to
DictList({'a': 1, 'b': 2}, {'b': 12, 'c': 13}, {'a': 'one', 'b': 'two'}, {'b': 'twelve', 'c': 'thirteen'})
Upvotes: 1
Views: 665
Reputation: 365707
To add two lists together, just use the +
operator.
And to create one of your objects out of a list of dicts instead of a bunch of separate dict arguments, just use *
to unpack the list.
So:
def __add__(self, other):
return type(self)(*(self.dl + other.dl))
Upvotes: 3