Skip to content

Instantly share code, notes, and snippets.

@technocrat
Created January 13, 2015 02:50
Show Gist options
  • Save technocrat/4d59279ba489b63489c7 to your computer and use it in GitHub Desktop.
Save technocrat/4d59279ba489b63489c7 to your computer and use it in GitHub Desktop.
Python snippet to sort in arbitrary order
from collections import defaultdict
def str_md(lexicon,key, value):
"""Generic append key, value to lexicon"""
lexicon.setdefault(key,value)
# Desired sort order
complist = ['Red', 'Apple', 'Green', 'Tea', 'Purple', 'Haze']
# Dictionary order
alphalist = sorted(complist)
# Create empty dictionary
D = {}
# Fill dictionary with item:index
for k,v in enumerate(complist):
str_md(D,k,v)
# Switch key and value
inv_map = {v: k for k, v in D.items()}
# Output the alphabetized list in desired order and then reverse
sorted(alphalist, key=inv_map.__getitem__)
sorted(alphalist, key=inv_map.__getitem__, reverse=True)
# See http://goo.gl/sDbhRQ for other ways to do this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment