Python: random order

Oracle SQL has a function for ordering as follows:

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 dictation by his keys. And this order is not necessarily in alphabetical order or anything - I define the order.

+3
source share
6 answers

You yourself cannot order a dictation, but you can convert it to a list of tuples (key, value), and you can sort them.

To do this, use the .items () method. For example,

>>> {'a': 1, 'b': 2}
{'a': 1, 'b': 2}
>>> {'a': 1, 'b': 2}.items()
[('a', 1), ('b', 2)]

- . cmp , , . , , :

sorted(somedict.items(), key=lambda x: {'carrot': 2, 'banana': 1, 'apple':3}[x[0]])

dict, , , dict.

+4

key named 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)

, list.index, dict.get.

#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)
+15

Python dict - hashmap, . , keys().

sorted() .

sortedKeys = sorted(dictionary, {"carrot": 2
                                ,"banana": 1
                                ,"apple":  3}.get);
+1

; - , .

, :

keys = myDict.keys()
sorted_keys = sorted(keys, myCompare)
+1

A dict . .

list.sort() ().

If you need to sort by several keys, just concatenate them in the tuple and sort by tuple.

0
source

Source: https://habr.com/ru/post/1705185/


All Articles