Dictionary wrong order – JSON

To post what has already been said in comments: Dictionaries are “unordered collections”. They do not have any order at all to their key/value pairs. Period.

If you want an ordered collection, use something other than a dictionary. (an array of single-item dictionaries is one way to do it.) You can also write code that loads a dictionary’s keys into a mutable array, sorts the array, then uses the sorted array of keys to fetch key/value pairs in the desired order.

You could also create your own collection type that uses strings as indexes and keeps the items in sorted order. Swift makes that straightforward, although it would be computationally expensive.

Leave a Comment