Array of dictionaries. Get the values of a specific key

var arrayDictionaries: [[String: Any]] = [["key1": 1.1, "key2": 2.1, "key3": "value3.1"], ["key1": "value1.2", "key2": "value2.2", "key3": "value3.3"]]

How can I get all the values of a specific key? In this simplified code, how to print all the key3

let allKey3 = arrayDictionaries.compactMap { $0["key3"] }

will give you ["value3.1", "value3.3"].

Would you like me to describe how compactMap works?

1 Like

Yes! please explain it. It is new for me

Let's start with a map. It takes a function, and keeps applying it for every element, and then returns all of them as an array

let arr = [1, 2, 3]
func multiplyByTwo(_ integer: Int) -> Int {
    return integer * 2
print( // [2, 4, 6]

but usually you don't want to make a function just to pass it to map, so usually we use a closure for that. $0 here means the (first) argument to the closure.

let arr = [1, 2, 3]
print( { $0 * 2 }) // [2, 4, 6]

So let's try to use map to get all all key3 from the array of dictionaries (I added a third dictionary to better make my point)

var arrayDictionaries: [[String: Any]] = [["key1": 1.1, "key2": 2.1, "key3": "value3.1"], ["key1": "value1.2", "key2": "value2.2", "key3": "value3.3"], ["key1": "value1.3"]]
print( { $0["key3"] }) // [Optional("value3.1"), Optional("value3.3"), nil]

It does what we want, which is to extract all key3, but everything is optional and there is a nil. To get rid of that, we use compactMap, which is just like map, but skips the nils afterwards. Notice how there are only two values extracted from three dictionaries

var arrayDictionaries: [[String: Any]] = [["key1": 1.1, "key2": 2.1, "key3": "value3.1"], ["key1": "value1.2", "key2": "value2.2", "key3": "value3.3"], ["key1": "value1.3"]]
print(arrayDictionaries.compactMap { $0["key3"] }) // ["value3.1", "value3.3"]

Very well explained. I understand. I have been many hours with this and you solved in a few minutes.

Terms of Service

Privacy Policy

Cookie Policy