Convert arrays to Dictionary

You can create a new Dictionary by mapping two sequences one is to one or by mapping a sequence of keys and values according to a custom logic; let’s take a look at both the methods:

  • Mapping two sequences (arrays) one is to one: Consider that you have two sequences personNames and ages as shown here:
 let personNames = ["Alex", "Tom", "Ravi", "Raj", "Moin"]
let ages = [23, 44, 53, 14, 34]

You can create a Dictionary contacts by joining these two arrays, as follows:

let contacts = Dictionary(uniqueKeysWithValues: zip(personNames, ages)) 

The output will be this:

["Tom": 44, "Raj": 14, "Moin": 34, "Ravi": 53, "Alex": 23]
  • Create a new Dictionary by mapping an array of keys and values according to a custom logic. Suppose you have two arrays- one with Strings representing all the odd numbers in words and other one with integers from 1 to 10:
let oddKeys = ["one", "three", "five", "seven", "nine"]
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • Now, consider that you want to create a Dictionary in which you want to map the String values to corresponding int values; you can do this as follows:
numbers = numbers.filter { $0 % 2 != 0 }
let oddDictionary = Dictionary(uniqueKeysWithValues: zip(oddKeys, numbers))
print(oddDictionary)
  • The output will be this:
["six": 6, "four": 4, "eight": 8, "ten": 10, "two": 2]

Easy, isn’t it!