---
title: "init(grouping:by:)"
framework: swift
role: symbol
role_heading: Initializer
path: "swift/dictionary/init(grouping:by:)"
---

# init(grouping:by:)

Creates a new dictionary whose keys are the groupings returned by the given closure and whose values are arrays of the elements that returned each key.

## Declaration

```swift
init<S, E>(grouping values: S, by keyForValue: (S.Element) throws(E) -> Key) throws(E) where Value == [S.Element], S : Sequence, E : Error
```

## Parameters

- `values`: A sequence of values to group into a dictionary.
- `keyForValue`: A closure that returns a key for each element in values.

## Discussion

Discussion The arrays in the “values” position of the new dictionary each contain at least one element, with the elements in the same order as the source sequence. The following example declares an array of names, and then creates a dictionary from that array by grouping the names by first letter: let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"] let studentsByLetter = Dictionary(grouping: students, by: { $0.first! }) // ["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]] The new studentsByLetter dictionary has three entries, with students’ names grouped by the keys "E", "K", and "A".

## See Also

### Creating a Dictionary

- [init()](swift/dictionary/init().md)
- [init(minimumCapacity:)](swift/dictionary/init(minimumcapacity:).md)
- [init(uniqueKeysWithValues:)](swift/dictionary/init(uniquekeyswithvalues:).md)
- [init(_:uniquingKeysWith:)](swift/dictionary/init(_:uniquingkeyswith:).md)
