Skip to content

Instantly share code, notes, and snippets.

@voodoonofx
Last active August 29, 2015 14:02
Show Gist options
  • Save voodoonofx/100ea0b6ff091856b965 to your computer and use it in GitHub Desktop.
Save voodoonofx/100ea0b6ff091856b965 to your computer and use it in GitHub Desktop.
Sorting a list of dicts on a complex key
# This gist can be seen live on http://codepad.org/gVPznGJ8
my_structure = [
{
'name': 'david',
'key': {
'subkey': 'value2',
},
},
{
'name': 'david',
'key': {
'subkey': 'value3',
},
},
{
'name': 'jim',
'key': {
'subkey': 'value1',
},
},
{
'name': 'bob',
'key': {
'subkey': 'value4',
},
},
]
# Define our sort function, which given an item in the list above,
# returns a tuple of important keys to sort on
sort_function = lambda x: (x.get('name'), x.get('key', {}).get('subkey'))
print(u'Using sorted, which uses a tuple of keys to sort a deep tree on')
print(sorted(my_structure, key=sort_function))
print(u'Using inline sort')
my_structure.sort(key=sort_function)
print(my_structure)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment