Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: arbitrary order by

In Oracle SQL there is a feature to order as follow:

order by decode("carrot" = 2
               ,"banana" = 1
               ,"apple" = 3)

What is the best way to implement this in python?

I want to be able to order a dict by its keys. And that order isn't necessarily alphabetically or anything - I determine the order.

like image 841
user37986 Avatar asked Mar 23 '09 15:03

user37986


People also ask

What does .sort do in Python?

Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.

Is there an ordered list in Python?

Yes, the order of elements in a python list is persistent.

How do you sort a list in ascending order in Python?

Python List sort() - Sorts Ascending or Descending List. The list. sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator.

How do you sort a list without sorting in Python?

You can use Nested for loop with if statement to get the sort a list in Python without sort function. This is not the only way to do it, you can use your own logic to get it done.


1 Answers

Use the key named keyword argument of sorted().

#set up the order you want the keys to appear here
order = ["banana", "carrot", "apple"]

# this uses the order list to sort the actual keys.
sorted(keys, key=order.index)

For higher performance than list.index, you could use dict.get instead.

#this builds a dictionary to lookup the desired ordering
order = dict((key, idx) for idx, key in enumerate(["banana", "carrot", "apple"]))

# this uses the order dict to sort the actual keys.
sorted(keys, key=order.get)
like image 86
recursive Avatar answered Sep 30 '22 17:09

recursive