按键排序字典 [英] Sort Dictionary by keys

查看:141
本文介绍了按键排序字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Swift中排序一个字典。我有一个字典,如:

 A=> Array [] 
Z=> Array []
D=> Array []

等。我想要它像

 A=> Array [] 
D=> Array []
Z=>数组[]

等。



在SO上尝试了许多解决方案,但没有人为我工作。我正在使用XCode6 Beta 5,其中一些是给编译器错误,一些解决方案提供了例外。所以任何人都可以发布字典排序的工作副本。

解决方案

  let dictionary = 
A:[1,2],
Z:[3,4],
D:[5,6]
]

let sortedKeys = Array(dictionary.keys).sorted(<)// [A,D,Z]

编辑:



上述代码中排序的数组只包含键值,而值必须从原始字典检索。然而,'Dictionary'也是(key,value)对的'CollectionType',我们可以使用全局'sorted'函数来获取包含键和值的排序数组,如下所示:

 code> let sortedKeysAndValues = sorted(dictionary){$ 0.0 < $ 1.0 
println(sortedKeysAndValues)// [(A,[1,2]),(D,[5,6]),(Z,[3,4])]

EDIT2:每月更改的Swift语法目前喜欢

  let sortedKeys = Array(dictionary.keys).sort(<)// [A,D,Z] 

全部已排序已被弃用。


I want to sort a dictionary in Swift. I have a dictionary like:

"A" => Array[]
"Z" => Array[]
"D" => Array[]

etc. I want it to be like

"A" => Array[]
"D" => Array[]
"Z" => Array[]

etc.

I have tried many solutions on SO but no one worked for me. I am using XCode6 Beta 5 and on it some are giving compiler error and some solutions are giving exceptions. So anyone who can post the working copy of dictionary sorting.

解决方案

let dictionary = [
    "A" : [1, 2],
    "Z" : [3, 4],
    "D" : [5, 6]
]

let sortedKeys = Array(dictionary.keys).sorted(<) // ["A", "D", "Z"]

EDIT:

The sorted array from the above code contains keys only, while values have to be retrieved from the original dictionary. However, 'Dictionary' is also a 'CollectionType' of (key, value) pairs and we can use the global 'sorted' function to get a sorted array containg both keys and values, like this:

let sortedKeysAndValues = sorted(dictionary) { $0.0 < $1.0 }
println(sortedKeysAndValues) // [(A, [1, 2]), (D, [5, 6]), (Z, [3, 4])]

EDIT2: The monthly changing Swift syntax currently prefers

let sortedKeys = Array(dictionary.keys).sort(<) // ["A", "D", "Z"]

The global sorted is deprecated.

这篇关于按键排序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆