1

How do I sort class instances in the list based on the length of the pool?

Example: Current value in dictionary: {"Metal":[['A', 20, 50, 'Wide']], "Wood":[['B', 50, 20, 'Thin'], ['C', 30, 30, 'Wide']]

Sorted value in dictionary: {"Metal":[['A', 20, 50, 'Wide']], "Wood":[['C', 30, 30, 'Wide'], ['B', 50, 20, 'Thin']]

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 sort(self):
       ????

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

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

    @property
    def length(self):
        return self._length

schizetia
  • 29
  • 4
  • Does this answer your question? [How to sort a list of objects based on an attribute of the objects?](https://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects) – buran Oct 19 '22 at 05:31
  • You need to implement some magic methos for `Pool` class – buran Oct 19 '22 at 05:31

1 Answers1

4

Both list.sort() for in-place sorting and sorted for returning a new list accept a key= callable argument that accepts the object to be sorted and should return its "sort key".

self._pools["Metal"].sort(key=lambda pool: pool.length)
AKX
  • 152,115
  • 15
  • 115
  • 172