Cesare
Cesare

Reputation: 9419

Getting values out of dictionaries which have arrays as values

I have a dictionary which contains languages as values and the initial character of every language name (A, B, C, ...) as for the key.

var dictionary = [Character: [Language]]()

I would like to get all the languages out of the dictionary in the form of an array. To do so, I do

let languages = dictionary.values // Dictionary<Character, [Language]>.Values

That's not an array. I try to get the array like this

let languages = Array(tableViewSource.values) // [[Language]]

This returns an array of an array. How do I just get an array of languages? I saw the merge(_:uniquingKeysWith:) but I don't need to merge dictionaries.

Upvotes: 0

Views: 79

Answers (3)

Martin R
Martin R

Reputation: 539745

If you want a single array (concatenating all dictionary values) then

Array(dictionary.values.joined())

does the trick. (This creates the final array without creating any additional intermediate arrays.)

Example:

let dictionary: [Character: [String]] = ["E": ["espanol", "english"], "G": ["german", "greek"]]
let langs = Array(dictionary.values.joined())
print(langs) // ["german", "greek", "espanol", "english"]

Note that the order of key/value pairs in a dictionary is unspecified. An alternative is

let dictionary: [Character: [String]] = ["E": ["espanol", "english"], "G": ["german", "greek"]]
let langs = dictionary.keys.sorted().flatMap { dictionary[$0]! }
print(langs) // ["espanol", "english", "german", "greek"]

which gives the languages sorted by the corresponding keys.

Upvotes: 1

Mr. Xcoder
Mr. Xcoder

Reputation: 4795

Martin R's and Sh_Khan's answers outline the standard ways of doing this (you basically just want to flatten an array). However I'd like to show a more "manual" approach:

var langs = [String]()
for lang_list in dictionary.values {
    langs.append(contentsOf: lang_list)
}

Alternatively, you can use the += operator instead of .append(contentsOf:). An easier way of doing this would be using flatMap(_:):

dictionary.values.flatMap { $0 }

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

let allLangs = nestedArr.reduce([], +)

Upvotes: 2

Related Questions