Home > Back-end >  Retrieving values from another class
Retrieving values from another class

Time:10-12

How can I remove a value from a list that is stored in a dictionary in a Class through the del method in the PoolSet class?

Thanks!

class PoolSet:
    def __init__ (self, ownerId, owner)
        self._ownerId = owner
        self._pools = {"Metal":[],"Wood":[]}

    #example of appending the Pool object into list based on the dictionary key
    self._pools["Metal"].append(Pool(label, length, width, grip))

    def del(label):
       ????

class Pool:
    def __init__(self, label, length, width, grip):

    @property
    def label(self):
        return self._label

#sample dictionary
{"Metal":[['A', 20, 50, 'Wide']], "Wood":[['B', 50, 20, 'Thin'], ['C', 30, 30, 'Wide']]

For example, if a user inputs the label name of a Pool (i.e, A), if found in the list in the dictionary, the del method will remove the whole attributes of that label (i.e remove [A, 20, 50, Wide]

*Note: The label is unique so there won't be duplicates in the dictionary

CodePudding user response:

If list elements are Pool objects:

def del(label):
    for key, value in self._pools.items():
        for i, pool in enumerate(self._pools[key]):
            if pool.label == label:
                _ = self._pools[key].pop(i)
                break

If list elements are list objects:

def del(label):
    for key, value in self._pools.items():
        for i, elem in enumerate(self._pools[key]):
            if elem[0] == label:
                _ = self._pools[key].pop(i)
                break

CodePudding user response:

the delete_pool function creates a copy of each list to iterate through and then removes any pools with the label given.

I've added a repr and a short example at the end to demonstrate.

class PoolSet:
    def __init__ (self, owner):
        self._ownerId = owner
        self._pools = {"Metal":[],"Wood":[]}

    def delete_pool(self, label):
        for material_type in self._pools:
            for pool in self._pools[material_type][:]:
                if pool.label == label:
                    self._pools[material_type].remove(pool)

class Pool:
    def __init__(self, label, length, width, grip):
        self.label = label
        self.length = length
        self.width = width
        self.grip = grip
    
    def __repr__(self):
        return f'Pool({self.label=}, {self.length=}, {self.width=}, {self.grip=})'


pool_set = PoolSet('schizetia')
pool_a = Pool('A', 20, 50, 'Wide')
pool_b = Pool('B', 50, 20, 'Thin')
pool_c = Pool('C', 30, 30, 'Wide')

pool_set._pools["Metal"].append(pool_a)
pool_set._pools["Wood"].append(pool_b)
pool_set._pools["Wood"].append(pool_c)

pool_set.delete_pool('B')

print(pool_set._pools)

Output

{'Metal': [Pool(self.label='A', self.length=20, self.width=50, self.grip='Wide')], 'Wood': [Pool(self.label='C', self.length=30, self.width=30, self.grip='Wide')]}
  • Related