I defined a class named DictList
. The DictList
class represents a list of dict, with some keys appearing in more than one dict.It has one parameter: it matches one or more arguments( must be dictionary).
class DictList:
def __init__(self,*args):
self.n = args
Like :
A = DictList({'a':1, 'b':2, 'c':3}, {'c':5, 'd':7, 'e':16}, {'e':25, 'f':29)
Now I want to define a add method in this class. It will add two DictList together or add one DictList and one dictionary.
Example:
>>> A1 = DictList(dict(a=1,b=2), dict(b=12,c=13))
>>> A2 = DictList(dict(a='hi',b='hello'), dict(b='good',c='nice'))
>>> A1+A2
DictList({'a': 1, 'b': 2}, {'b': 12, 'c': 13}, {'a': 'hi', 'b': 'hello'}, {'b': 'good', 'c': 'nice'})
>>> A2 + A1
DictList( {'a': 'hi', 'b': 'hello'}, {'b': good', 'c': 'nice'},{'a': 1, 'b': 2}, {'b': 12, 'c': 13})
My idea is to create a new DictList with a list of dictionaries that contains all the dicts in the two DictLists or one DictList and one dict.
def __add__(self,new):
if type(new) == DictList:
print(DictList( all dicts from self and new ))
if type(new) == dict:
print(DictList(all dicts from self and new))
But I don't know how to get every dict in the two DictList and put all of them into the new DictList.How can I do?
Return a new DictList
with the joined self.n
argument lists. If you want to add regular dictionaries, too, check the type of the instance. You may want to define __radd__
to handle dict + DictList
instead of only DictList + dict
.
class DictList:
def __init__(self,*args):
self.n = args
def __add__(self,new):
L = list(self.n)
if isinstance(new,DictList):
L.extend(new.n)
elif isinstance(new,dict):
L.append(new)
else:
raise TypeError('Must be instance of DictList or dict')
return DictList(*L)
def __radd__(self,new):
return self.__add__(new)
def __repr__(self):
return 'DictList'+repr(self.n)
Demo:
>>> d = DictList(dict(a=1,b=2,c=3),dict(a=2,b=3,e=4))
>>> e = DictList(dict(a=4,c=2,e=3))
>>> d+e
DictList({'b': 2, 'c': 3, 'a': 1}, {'b': 3, 'a': 2, 'e': 4}, {'c': 2, 'a': 4, 'e': 3})
>>> d+dict(x=1,y=2)
DictList({'b': 2, 'c': 3, 'a': 1}, {'b': 3, 'a': 2, 'e': 4}, {'x': 1, 'y': 2})
>>> dict(x=1,y=2)+d
DictList({'b': 2, 'c': 3, 'a': 1}, {'b': 3, 'a': 2, 'e': 4}, {'x': 1, 'y': 2})
>>> d+5
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Users\metolone\Desktop\x.py", line 12, in __add__
raise TypeError('Must be instance of DictList or dict')
TypeError: Must be instance of DictList or dict
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.