3

how can I sort a dictionary in ascending order of values?

I have something like this :

["user1": 3764, "user5": 23, "user87": 875, "user21": 54987, ... ]

And I would like to get a dictionary ranked in ascending order of its values, like this :

["user5": 23, "user87": 875, "user1": 3764, "user21": 54987, ...] 
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Thomas
  • 323
  • 3
  • 18
  • 1
    As has been discussed here countless times, dictionaries have no order. – rmaddy Aug 20 '19 at 17:02
  • 1
    Dictionaries guarantee no order (in memory), but there are applications where an ordered dict is useful. Depending on your final goal, you could take a look a `OrderedDict` or write a `class` around `dict` that gives you ordered output in the way you want it. – Sergio Pulgarin Aug 20 '19 at 17:14

1 Answers1

2

Try this.

let userRankDict = ["user1": 3764, "user5": 23, "user87": 875, "user21": 54987]
let sortedUserRankDict = userRankDict.sorted{ $0.value < $1.value }
print(sortedUserRankDict)

Sorted userRankDict:

[(key: "user5", value: 23), (key: "user87", value: 875), (key: "user1", value: 3764), (key: "user21", value: 54987)]

Vinu Jacob
  • 393
  • 2
  • 15