Skip to content

Instantly share code, notes, and snippets.

@faniska
Created September 9, 2022 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save faniska/9c9148595b97935c4979c4693f7d0e5d to your computer and use it in GitHub Desktop.
Save faniska/9c9148595b97935c4979c4693f7d0e5d to your computer and use it in GitHub Desktop.
Sort python list containing tuples with dict
#!/usr/bin/env python
class CustomCompare(object):
def __init__(self, obj, order):
self.obj = obj
self.order = order
def __lt__(self, other):
return self._index_of(self.obj) < self._index_of(other.obj)
def __gt__(self, other):
return self._index_of(self.obj) > self._index_of(other.obj)
def __eq__(self, other):
return self._index_of(self.obj) == self._index_of(other.obj)
def __le__(self, other):
return self._index_of(self.obj) <= self._index_of(other.obj)
def __ge__(self, other):
return self._index_of(self.obj) >= self._index_of(other.obj)
def __ne__(self, other):
return self._index_of(self.obj) != self._index_of(other.obj)
def _index_of(self, obj):
name = obj[2]['name']
if name in self.order:
return self.order.index(name)
else:
return len(self.order)
a = [
(0, 3, {'name': 'C'}),
(0, 2, {'name': 'B'}),
(0, 1, {'name': 'A'}),
(0, 4, {'name': 'D'}),
]
x = sorted(a, key=lambda l: CustomCompare(l, order=['A', 'C', 'B', 'D']))
print(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment