Home > Software design >  Get key for min value in python dict of class objects
Get key for min value in python dict of class objects

Time:01-19

I have a custom class (simplified) like this:

class SoftMatch:
    def __init__(self, time_d):       
        self.time_delta = time_d

and a dict with instances of this class:

softmatches = {"Nikon": SoftMatch(1), "Canon": SoftMatch(2), "Sony": SoftMatch(3)}

I need to get the key and preferrably the value for the SoftMatch object with the lowest "self.time_delta".

Could I do this with the python "min" function or a dict comprehension or a combo of those?

CodePudding user response:

This should work:

>>> min(softmatches.items(), key=lambda x: x[1].time_delta)
('Nikon', <__main__.SoftMatch at 0x7f9081b81120>)
  • Related