I have some custom objects and dictionaries that I want to sort. I want to sort both the objects the dictionaries together. I want to sort the objects by an attribute and the dictionaries by a key.
object.name = 'Jack'
d = {'name':'Jill'}
sort_me =[object, d]
How do I sort this list using the object’s name attribute and the dictionary’s ‘name’ key?
What you are almost certainly looking for is to use the key= option for sorted(), which provides a function which returns an arbitrary sort key for each element. This function can check the type of its argument and take various actions. For instance:
More information can be found on the Python wiki
RichieHindle’s suggestion of using isinstance is a good one. And while I was at it I thought it might be nice to support arbitrary element names instead of hardcoding ‘name’:
Which you can use like so: