简体   繁体   中英

Unpack a list of dictionaries and set each to its own variable

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'})

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))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM