如何遍历数组并将每个项目分配给每个字典键

时间:2019-09-19 18:35:34

标签: arrays swift dictionary

我有一个数组和一个字典

var list = ["A", "B", "C","D"]

var dict = [
    "Chapter 1 Body" : "",
    "Chapter 2 Body" : "",
    "Chapter 3 Body" : "",
    "Chapter 4 Body" : ""
]

我想遍历列表数组并将每个项目分配给字典的每个键。这是我打印字典时的预期输出:

["Chapter 1 Body": "A", "Chapter 2 Body": "B", "Chapter 3 Body": "C", "Chapter 4 Body": "D"]

注意:订单应与打印输出相同。

2 个答案:

答案 0 :(得分:1)

您可以使用zip并对键进行排序(如果字母排序顺序是字典键的正确顺序)

dict = zip(dict.keys.sorted(), list).reduce(into: [:]) {$0[$1.0] = $1.1} 

如果键以其他顺序排序,则需要将它们按正确的顺序放在数组中,但解决方案基本相同

var chapters = ["Chapter 1 Body", "Chapter 2 Body", "Chapter 3 Body", "Chapter 4 Body"]
let dict = zip(chapters, list).reduce(into: [:]) {$0[$1.0] = $1.1} 

答案 1 :(得分:1)

var i = 0
for k in dict.keys.sorted() {
    dict[k] = list[i]
    i += 1
}