schizetia
schizetia

Reputation: 29

Sorting class instances in a List

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

Upvotes: 1

Views: 55

Answers (1)

AKX
AKX

Reputation: 168863

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)

Upvotes: 4

Related Questions