Skip to content

Instantly share code, notes, and snippets.

@MetroWind
Created January 10, 2020 02:54
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 MetroWind/b180104292b2c69c92bcb9f66a58ba06 to your computer and use it in GitHub Desktop.
Save MetroWind/b180104292b2c69c92bcb9f66a58ba06 to your computer and use it in GitHub Desktop.
A function that returns a function that sorts according to a list of keys
def props_to_sort_lambda(*props):
"""Return a function that sorts according to property list `props`.
The sort is supposed to apply on a list of dictionaries with the same set of
keys. Argument `props` is a list of keys for the dicts.
Example:
xs = [{"aaa": 1, "bbb": 2, ...}, {"aaa": 2, "bbb": 3, ...}, ...]
sorted_xs = props_to_sort_lambda("-aaa", "bbb")(xs)
This sorts `xs` first by "bbb", and then by "aaa" but reversed. In another
word, the result would contain the largest aaa in the beginning, and if two
dicts have the same aaa, the one that has the smaller bbb comes first.
"""
if len(props) == 0:
return lambda x:x
prop = props[0]
reverse = False
if prop[0] == '-':
prop = prop[1:]
reverse = True
return lambda xs: sorted(props_to_sort_lambda(*(props[1:]))(xs),
key=lambda x:x[prop], reverse=reverse)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment