Reputation:
I’m using a nested dictionary data structure to keep a track of a bunch of NSLayoutConstraint
s, [String: [String: NSLayoutConstraint]]
to be specific. But for my situation, let’s consider the following simpler example:
var myNestedDictionary = [String: [Int: Double]]()
myNestedDictionary["squares"] = [1: 1.0, 2: 4.0, 3: 9.0, 4: 16.0]
myNestedDictionary["cubes"] = [1: 1.0, 2: 8.0, 3: 27.0, 4: 64.0]
myNestedDictionary["factorials"] = [1: 1.0, 2: 2.0, 3: 6.0, 4: 24.0]
How do I extract into a [Double]
all the values, not the key-value pairs of one dictionary entry, e.g. how do I get [1.0, 8.0, 27.0, 64.0]
from myNestedDictionary["cubes"]
?
Upvotes: 0
Views: 279
Reputation: 487
The simplest way would be to just map the dictionary to an array:
let values = myNestedDictionary["cubes"]?.map({$0.1})
This won't necessarily stick with the order implied by the keys, as dictionaries are unordered. If you want to keep the ascending order, you could sort on the keys first and then use the sorted keys in the mapping:
let values = myNestedDictionary["cubes"]?.keys.sort().flatMap {myNestedDictionary["cubes"]![$0]!}
Upvotes: 1