Swift – Create Dictionary from Arrays

Welcome to Swift Tutorial. In our previous tutorial, we learned to create a dictionary that is empty or with some initial (key, value) pairs. In this tutorial, we will learn how to create a Dictionary using Arrays in Swift.

The usual approach is to pair a key array with a value array by using zip(_:_:), and then pass the resulting sequence of tuples to a Dictionary initializer. Each element in the first array becomes a key, and the element at the same position in the second array becomes its value.

Create a Swift Dictionary from Two Arrays with zip(_:_:)

Two arrays are required to create a dictionary in this form. One array supplies the keys and the other supplies the values. For a complete one-to-one mapping, both arrays should contain the same number of elements.

Following is the syntax to create a dictionary from two Arrays.

</>
Copy
var array1 = [key1, key2, key3]
var array2 = [value1, value2, value3]

let myDictionary = Dictionary(uniqueKeysWithValues: zip(array1, array2))

The zip function pairs the first key with the first value, the second key with the second value, and so on. The Dictionary(uniqueKeysWithValues:) initializer then creates the dictionary from those pairs.

Requirements for Swift Array-to-Dictionary Conversion

  • The key type must conform to Hashable. Standard key types such as String, Int, and UUID already meet this requirement.
  • Every key passed to Dictionary(uniqueKeysWithValues:) must be unique. Duplicate keys cause a runtime error.
  • Check that both arrays have equal counts when every value must be retained. A zipped sequence contains only pairs that can be formed from both input sequences, so extra elements in the longer array are not included.
  • Do not depend on the printed or iterated order of dictionary entries. Use explicit keys or sort the entries when a stable presentation order is required.

Apple’s Dictionary initializer documentation specifies that the keys supplied to uniqueKeysWithValues must be unique.

Example 1 – Create a Swift Dictionary from Arrays

In the following example, we take two arrays. The first array is a String Array of names and the second array is an Integer Array of marks. Assuming that the names array contains unique strings that can be used as keys, the following program creates a Dictionary from the two arrays. Also, we shall print the (key, value) pairs of the dictionary.

main.swift

</>
Copy
var names = ["Mohan", "Raghu", "John"]
var marks = [75, 82, 79]

let myDictionary = Dictionary(uniqueKeysWithValues: zip(names, marks))

for (_, key_value) in myDictionary.enumerated() {
   print("\(key_value)")
}

Output

(key: "Raghu", value: 82)
(key: "John", value: 79)
(key: "Mohan", value: 75)

The dictionary contains the same name-to-mark mappings shown above, but the order of the printed entries can differ between runs or Swift environments. Access a specific result with a key, for example myDictionary["Mohan"].

Validate Equal Array Lengths Before Creating the Dictionary

When unequal array lengths indicate invalid input, compare the counts before calling zip. The following example stops immediately instead of silently omitting unmatched elements.

</>
Copy
let names = ["Mohan", "Raghu", "John"]
let marks = [75, 82, 79]

guard names.count == marks.count else {
    fatalError("The key and value arrays must have the same number of elements.")
}

let marksByName = Dictionary(uniqueKeysWithValues: zip(names, marks))

print(marksByName["Raghu"] ?? 0)

Output

82

Handle Duplicate Array Keys with uniquingKeysWith

Use Dictionary(_:uniquingKeysWith:) when the key array may contain duplicates. Its closure receives the existing value and the new value for each repeated key. You can keep the first value, keep the last value, or combine both values.

The next example keeps the last mark associated with a repeated name.

</>
Copy
let names = ["Mohan", "Raghu", "Mohan"]
let marks = [75, 82, 91]

let latestMarks = Dictionary(
    zip(names, marks),
    uniquingKeysWith: { _, newValue in newValue }
)

print(latestMarks["Mohan"] ?? 0)
print(latestMarks["Raghu"] ?? 0)

Output

91
82

To keep the first value instead, return the existing value from the closure: { existingValue, _ in existingValue }.

Convert One Swift Array to a Dictionary with reduce(into:)

When keys and values must be calculated from each element of one array, reduce(into:) provides a direct way to build the dictionary. This is useful when the output is not already separated into parallel key and value arrays.

</>
Copy
let words = ["swift", "array", "dictionary"]

let characterCounts = words.reduce(into: [String: Int]()) { result, word in
    result[word] = word.count
}

print(characterCounts["dictionary"] ?? 0)

Output

10

Group Swift Array Elements into Dictionary Values

Dictionary(grouping:by:) is appropriate when several array elements should share the same key. Unlike a one-value-per-key conversion, the resulting dictionary stores an array of matching elements for each key.

</>
Copy
let names = ["Mohan", "Meera", "Raghu", "Ravi"]

let namesByFirstLetter = Dictionary(grouping: names) { name in
    name.first!
}

print(namesByFirstLetter["M"] ?? [])
print(namesByFirstLetter["R"] ?? [])

Output

["Mohan", "Meera"]
["Raghu", "Ravi"]

Choosing the Correct Swift Dictionary Conversion Method

Input and requirementRecommended Swift API
Two arrays with unique keysDictionary(uniqueKeysWithValues: zip(keys, values))
Two arrays that may contain duplicate keysDictionary(zip(keys, values), uniquingKeysWith:)
One array whose elements must be transformed into key-value pairsreduce(into:)
One array whose elements must be collected under shared keysDictionary(grouping:by:)

Swift Array-to-Dictionary FAQs

How do I convert two arrays into a dictionary in Swift?

Use zip(keys, values) to create key-value tuples and pass them to Dictionary(uniqueKeysWithValues:). This method is suitable when every key is unique.

What happens when the Swift arrays have different lengths?

Only positions that have an element in both sequences can form zipped pairs. If unmatched elements must be treated as an error, compare the array counts before creating the dictionary.

How do I prevent a duplicate-key runtime error?

Use Dictionary(_:uniquingKeysWith:) and provide a closure that selects or combines values when a key occurs more than once.

Can I create a Swift dictionary from one array?

Yes. Use reduce(into:) when each element produces one key-value pair, or use Dictionary(grouping:by:) when multiple elements should be stored under the same key.

Swift Array-to-Dictionary QA Checklist

  • Confirm that the intended key type conforms to Hashable.
  • Verify whether duplicate keys are impossible or require an explicit conflict rule.
  • Check equal array counts when unmatched elements must not be discarded.
  • Test dictionary values by key instead of assuming iteration order.
  • Use Dictionary(grouping:by:) only when the required value type is an array of grouped elements.

Swift Array-to-Dictionary Conversion Summary

In this Swift Tutorial, we have learned to create a dictionary from two arrays of same length. We also covered count validation, duplicate-key handling, one-array conversion with reduce(into:), and grouped dictionaries with Dictionary(grouping:by:).