Sorting a heterogeneous list of objects in Python

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:

import types

class obj(object):
    def __init__(self, arg):
        self.name = arg

def extract_name(obj):
    if type(obj) is types.DictType:
        return obj['name']
    else:
        return obj.__dict__['name']

d = { 'name': 'Jill'}    
print sorted([obj('Jack'), d], key=extract_name)

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':

def extract_elem_v2(elem_name):
    def key_extractor(obj):
        dct = obj if isinstance(obj, dict) else obj.__dict__
        return dct[elem_name]
    return key_extractor

Which you can use like so:

print sorted(list_of_stuff, key=extract_elem_v2('name'))

Sorting HOW TO — Python 3.3.7 documentation, There is also a sorted() built-in function that builds a new sorted list from is to sort complex objects using some of the object's indices as keys. Sorting a Heterogeneous List of Custom Python Objects. Alright. Since Python is a dynamic language, it doesn't so much care about what objects we throw into lists. They can all be the same type, or they can all be different. So let's define another different object to use with our Custom object.

sort_me.sort(key=attr_or_itemgetter('name'))

Where attr_or_itemgetter():

class attr_or_itemgetter(object):
    def __init__(self, name):
        self.name = name
    def __call__(self, obj):
        try: return getattr(obj, name)
        except AttributeError:
            return obj[name]

NOTE: It intentionally doesn't check for dictionary type, therefore attr_or_itemgetter('items') applied to a dictionary will return dict.items method.

How to Sort a List, Tuple or Object (with sorted) in Python, Sorting a Heterogeneous List of Custom Python Objects. Alright. Since Python is a dynamic language, it doesn't so much care about what objects� A friend of mind, Ruiwen, just pointed out to me that Python has a sorted() function that can be used. The sorted() function takes in a list of objects, the key to sort by and returns the sorted list. This function uses Lamba which creates an anonymous function. So to sort our unsorted list of car names, we use

This worked for me. Note that sort() does not return the sorted list, but sorted() does, so if you want to pass this to a template, you should use sorted in the parameters, or sort before you pass the list as a parameter.

itemized_action_list = list(chain(detection_point.insertbodyaction_set.all(),
                                  detection_point.insertheaderaction_set.all(),
                                  detection_point.modifybodyaction_set.all(),
                                  detection_point.modifyheaderaction_set.all(),
                                  detection_point.removebodyaction_set.all(),
                                  detection_point.removeheaderaction_set.all(),
                                  detection_point.redirectaction_set.all()))

sorted(itemized_action_list, key=attrgetter('priority'))

wolever/safesort: Safely sort heterogeneous collections on Python 2 , Safely sort heterogeneous collections on Python 2 and 3 - wolever/safesort. As consistent as possible; Broadly sensible: objects with similar types will be� Python Server Side Programming Programming To sort a list of ints, floats, strings, chars or any other class that has implemented the __cmp__ method can be sorted just by calling sort on the list. If you want to sort the list in reverse order (descending), just pass in the reverse parameter as well.

new_list = [10,"m",20,30,"a","r",70,"d"]

def func(x):

if type(x) == str:

    return ord(x)+100

return x

new_list.sort(key=func)

print(new_list)

[10, 20, 30, 70, 'a', 'd', 'm', 'r']

Comparing and Sorting — Conservative Python 3 Porting Guide 1.0 , If you need to sort heterogeneous lists, or compare different types of objects, implement a key function to fully describe how disparate types should be ordered . To demonstrate how to take a custom list of objects and sort those objects by a specific property. In the case of this tutorial I have chosen to use a date property because sorting by date is a very real world example of something you may run into in the work place, but the same code would also work for numbers or strings as well.

Python List: Comprehension, Apend, Sort, Length, Reverse , Python lists can be homogeneous, meaning that they can contain the same type of objects; or heterogeneous, including different types of� Java Sort List. Here we will learn how to sort a list of Objects in Java. We can use Collections.sort() method to sort a list in the natural ascending order. All the elements in the list must implement Comparable interface, otherwise IllegalArgumentException is thrown. Let’s look at a quick example to sort a list of strings.

How to sort the objects in a list in Python?, To sort a list of ints, floats, strings, chars or any other class that has implemented the __cmp__ method can be sorted just by calling sort on the� The change usually manifests itself in sorting lists: in Python 3, lists with items of different types are generally not sortable. If you need to sort heterogeneous lists, or compare different types of objects, implement a key function to fully describe how disparate types should be ordered.

Sorted() function in Python, Sorted() function in Python � Iterable : sequence (list, tuple, string) or collection ( dictionary, set, frozenset) or any other iterator that needs to be�

Comments
  • +1. Minor suggestion: isinstance(obj, dict) would be neater, and would allow for classes derived from dict.
  • You're right, isinstance is a better choice there, not sure why I didn't think of that. Updated version appended to the answer. Thanks!
  • Thanks a lot Jack! This answer is beautiful.
  • __dict__ attribute is not available for all objects.
  • A) Corrections inline, that's what people read. The type(..) is thing has 0 merit to stay. B) is vars(obj) preferred over obj.__dict__? (vars is a less known builtin.)
  • I find this answer more Pythonic than the one based on type-checking (may be a little slower if there are plenty of dicts in the sequence being sorted, but all it takes to optimize it for that use is flipping what's the try body & what's the except body, and catching different exceptions;-0).
  • Welcome to SO. Try to be clear and precise in your examples. Without no additional info it is not possible to say what your list contains.