Reputation: 777
How can I sort the below array of dictionaries so that the keys of each dictionary are in ascending order, without creating anything new (using .sort not .sorted)? Any help is greatly appreciated, many thanks!!
Current array of dictionaries:
What I would like:
Code that isn't working:
var arrayOfDicts = [[2: 0, 3: 0, 1: 0], [2: 0, 1: 0], [2: 0, 1: 0], [2: 0, 1: 0]]
arrayOfDicts.sort(by: { $0.keys.first! > $1.keys.first! })
print(arrayOfDicts)
// prints [[2: 0, 3: 0, 1: 0], [2: 0, 1: 0], [2: 0, 1: 0], [2: 0, 1: 0]]
Upvotes: 0
Views: 76
Reputation: 535306
so that the keys of each dictionary are in ascending order
[[1: 0, 2: 0, 3: 0], [1: 0, 2: 0], [1: 0, 2: 0], [1: 0, 2: 0]]
To say "so that the keys of each dictionary are in ascending order" implies that you want to sort each actual dictionary (and that is what appears to be happening in your "what I would like" output). But a dictionary cannot be sorted; the notion is meaningless, because a dictionary has no order. The order in which its elements (or keys) are printed is random.
So what you're describing is impossible. You cannot want it. You may think you want it, but you don't. It would do you no good whatever; a "sorted" dictionary, if it existed, would change nothing, because it would not affect what the dictionary does, which is not to list elements in some order but to retrieve values by key.
Upvotes: 2