Swift - 按字母顺序和值在字典中排列第二个字典
Swift - Arrange Second Dictionary in Dictionary Alphabetically and by values
我有以下类型的字典:Dictionary<String,Dictionary<String,Int64>>
myDict["DictA"]!["ElementB"] = 8
myDict["DictA"]!["ElementC"] = 16
myDict["DictA"]!["ElementA"] = 32
我想按字母顺序排列我的第二本词典:
myDict["DictA"]!["ElementA"] = 32
myDict["DictA"]!["ElementB"] = 8
myDict["DictA"]!["ElementC"] = 16
并按值:
myDict["DictA"]!["ElementA"] = 32
myDict["DictA"]!["ElementC"] = 16
myDict["DictA"]!["ElementB"] = 8
我需要 arrangeAlphabetically(myDict:Dictionary<String, Int64>)->Dictionary<String, Int64>
类型的函数和另一个 arrangeByValue
类型的函数。如何实现?
字典本质上是无序的所以简而言之:你不能。
您可以按照您需要的顺序将您的值放入数组中,因为数组是有序的。
Dictionary
本质上是一种无序集合类型。同时,它是 (Key, Value)
对元组的序列。你可以获得 sorted()
这些元组。
var myDict:[String:[String:Int64]] = ["DictA":[:]]
myDict["DictA"]!["ElementA"] = 32
myDict["DictA"]!["ElementC"] = 16
myDict["DictA"]!["ElementB"] = 8
let sortedByKeyAsc = sorted(myDict["DictA"]!) { [=10=].0 < .0 } // by keys ascending
let sortedByValDesc = sorted(myDict["DictA"]!) { [=10=].1 > .1 } // by values descending
println(sortedByKeyAsc) // -> [(ElementA, 32), (ElementB, 8), (ElementC, 16)]
println(sortedByValDesc) // -> [(ElementA, 32), (ElementC, 16), (ElementB, 8)]
我有以下类型的字典:Dictionary<String,Dictionary<String,Int64>>
myDict["DictA"]!["ElementB"] = 8
myDict["DictA"]!["ElementC"] = 16
myDict["DictA"]!["ElementA"] = 32
我想按字母顺序排列我的第二本词典:
myDict["DictA"]!["ElementA"] = 32
myDict["DictA"]!["ElementB"] = 8
myDict["DictA"]!["ElementC"] = 16
并按值:
myDict["DictA"]!["ElementA"] = 32
myDict["DictA"]!["ElementC"] = 16
myDict["DictA"]!["ElementB"] = 8
我需要 arrangeAlphabetically(myDict:Dictionary<String, Int64>)->Dictionary<String, Int64>
类型的函数和另一个 arrangeByValue
类型的函数。如何实现?
字典本质上是无序的所以简而言之:你不能。
您可以按照您需要的顺序将您的值放入数组中,因为数组是有序的。
Dictionary
本质上是一种无序集合类型。同时,它是 (Key, Value)
对元组的序列。你可以获得 sorted()
这些元组。
var myDict:[String:[String:Int64]] = ["DictA":[:]]
myDict["DictA"]!["ElementA"] = 32
myDict["DictA"]!["ElementC"] = 16
myDict["DictA"]!["ElementB"] = 8
let sortedByKeyAsc = sorted(myDict["DictA"]!) { [=10=].0 < .0 } // by keys ascending
let sortedByValDesc = sorted(myDict["DictA"]!) { [=10=].1 > .1 } // by values descending
println(sortedByKeyAsc) // -> [(ElementA, 32), (ElementB, 8), (ElementC, 16)]
println(sortedByValDesc) // -> [(ElementA, 32), (ElementC, 16), (ElementB, 8)]