0

I have an associative array which I want to sort

  items = {1: [5, 30, 0.16666666666666666], 2: [10, 20, 0.5]}

I want to sort items by float value with descending order so after sorting I should get

 items = {2: [10, 20, 0.5], 1: [5, 30, 0.16666666666666666]} 

Note I want to sort mainly these 0.16666666666666666 and 0.5

Any help is welcomed!

1
  • I don't understand your logic. Your list values are unchanged. But your keys are visually the other way round. Except internally [and for all intents] dictionaries are not considered ordered (unless you are using Python 3.7). Commented Jul 23, 2018 at 15:58

1 Answer 1

1

You need to create a new dict based on the sorted items of items:

items = {k: v for k, v in sorted(items.items(), reverse=True)}

Note that this will only work for Python 3.6+ for which the order is guaranteed to be the insertion order. I'd recommend using a list or an OrderedDict instead.

Example:

>>> items = {1: [5, 30, 0.16666666666666666], 2: [10, 20, 0.5]}
>>> items = {k: v for k, v in sorted(items.items(), reverse=True)}    
>>> items
{2: [10, 20, 0.5], 1: [5, 30, 0.16666666666666666]}
Sign up to request clarification or add additional context in comments.

2 Comments

this solution is not working for this scenario {1: [60, 20, 3.0], 2: [100, 50, 2.0], 3: [120, 30, 4.0]} after {k: v for k, v in sorted(items.items(), reverse=True)} this is what I get {3: [120, 30, 4.0], 2: [100, 50, 2.0], 1: [60, 20, 3.0]}
try using a custom key for the call to sorted(): key=lambda item: item[1][-1], where the [1] means the value of the (key, value) tuple and [-1] accesses the last item of the array, which you said you want to sort by

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.