Home > Mobile >  I want find min element of object by attribute in a list of objects in Python
I want find min element of object by attribute in a list of objects in Python

Time:10-20

I want find min element of object (by days attribute) in a list of objects in Python, I have this code so far:

from operator import attrgetter
    
lists = json.loads("["   data   "]")
print(lists)
maintenance_cycle = min(lists,key=lambda r: r.days)
  • Console output:
[{'type': 'runtime', 'days': 1}]
  • Error:
'dict' object has no attribute 'days'

CodePudding user response:

Accessing dictionary keys is not like accessing class methods

Try this code

maintenance_cycle = min(lists, key=lambda r: r['days'])

Or

maintenance_cycle = min(lists, key=lambda r: r.get('days'))

Instead of

maintenance_cycle = min(lists,key=lambda r: r.days)

And tell me if its not working...

  • Related