0

Consider a dictionary 'a' if:

a = {6:32 , 1:15 , 3:45 , 2:12 , 5:46, 4:99}

I want to sort this dict by values with respect to its keys, such as this:

a = {2:12 , 1:15 , 6:32 , 3:45 , 5:46 , 4:99}

I wanted to know if it's possible without importing any modules.

Thanks

1 Answers1

-1

A dictionary has no sort order. But you can sort the keys and retrieve them in order. For example:

for k in sorted(a, key=lambda k: a[k]):
    print k, a[k]

The "key" lambda function specifies by which value to sort. In the example it sorts by the key's value in the dictionary.

Andomar
  • 232,371
  • 49
  • 380
  • 404
  • It sorts perfectly. As I wanted it to be in a dictionary, I edited the body of the loop as: a_sortedAsc = {} for k in sorted(a, key = lambda k: a[k]): a_sortedAsc.update({k: a[k]}) – Abdullah Surati Aug 13 '17 at 08:25
  • Please don't provide answer to a question that obviously has dupes and considering the linked dupe has 46 answers. Also there was [no attempt from OP whatsoever](https://meta.stackoverflow.com/questions/353940/why-would-a-question-thats-normally-too-broad-in-any-other-language-be-okay-i). – Ashwini Chaudhary Aug 13 '17 at 11:21
  • @AshwiniChaudhary: The question you marked as "duplicate source" does indeed have 46 contradicting and convoluted answers. One of the worst SO pages to land on from Google. – Andomar Aug 13 '17 at 17:11
  • 1
    How did your answer help? How is this better than using simple `dict.get`? If you see their [comment](https://stackoverflow.com/questions/45658112/sorting-a-dictionary-by-values/45658150?noredirect=1#comment78274924_45658150), they are still appending keys back to a normal dict. Means they learned nothing. :-( – Ashwini Chaudhary Aug 13 '17 at 17:15
  • @AshwiniChaudhary: well, my answer may not be the best, but why not try? One day there will hopefully be a better Q&A that you land on if you Google "python sort dictionary by value". – Andomar Aug 13 '17 at 17:24