Reputation: 992
I have Dictionary of type:Dictionary<String,Dictionary<String,Int64>>
myDict["DictA"]!["ElementB"] = 8
myDict["DictA"]!["ElementC"] = 16
myDict["DictA"]!["ElementA"] = 32
I want to arrange my second dictionary alphabetically:
myDict["DictA"]!["ElementA"] = 32
myDict["DictA"]!["ElementB"] = 8
myDict["DictA"]!["ElementC"] = 16
And by value:
myDict["DictA"]!["ElementA"] = 32
myDict["DictA"]!["ElementC"] = 16
myDict["DictA"]!["ElementB"] = 8
I need func of type arrangeAlphabetically(myDict:Dictionary<String, Int64>)->Dictionary<String, Int64>
and another one arrangeByValue
.How it will be done?
Upvotes: 1
Views: 73
Reputation: 51911
Dictionary
is essentially a unordered collection type. Meanwhile, it's a sequence of (Key, Value)
pair tuples. You can get sorted()
these tuples.
var myDict:[String:[String:Int64]] = ["DictA":[:]]
myDict["DictA"]!["ElementA"] = 32
myDict["DictA"]!["ElementC"] = 16
myDict["DictA"]!["ElementB"] = 8
let sortedByKeyAsc = sorted(myDict["DictA"]!) { $0.0 < $1.0 } // by keys ascending
let sortedByValDesc = sorted(myDict["DictA"]!) { $0.1 > $1.1 } // by values descending
println(sortedByKeyAsc) // -> [(ElementA, 32), (ElementB, 8), (ElementC, 16)]
println(sortedByValDesc) // -> [(ElementA, 32), (ElementC, 16), (ElementB, 8)]
Upvotes: 0
Reputation: 2810
Dictionary are by essence unordered so in a few words : you cannot.
You could put your values in arrays in the order you need as array are ordered.
Upvotes: 1