Created
January 13, 2015 02:50
-
-
Save technocrat/4d59279ba489b63489c7 to your computer and use it in GitHub Desktop.
Python snippet to sort in arbitrary order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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