-1

I have an array ([Dictionary<String, String>]) of dictionary, say,

let dict0 = ["0": 1, "1": 2, "2": 4]
let dict1 = ["0": 5, "1": 4, "2": 8]
let dict2 = ["0": 3, "1": 9, "2": 7]
let array = [dict0, dict1, dict2]

So it looks like the following.

[
  ["0": 1, "1": 2, "2": 4], 
  ["2": 8, "0": 5, "1": 4], 
  ["2": 7, "1": 9, "0": 3]
]

Let me assume that I have an array ([String]) of keys like

let keys = ["ant", "bee", "spider"]

Is there a simple way of changing my array's keys such that it will look like the following?

[
  ["ant": 1, "bee": 2, "spider": 4], 
  ["spider": 8, "ant": 5, "bee": 4], 
  ["spider": 7, "bee": 9, "ant": 3]
]

Thanks.

El Tomato
  • 6,479
  • 6
  • 46
  • 75

1 Answers1

0

Don't actually know what you mean by simple way but the following will get the job done.

let dict0 = ["0": 1, "1": 2, "2": 4]
let dict1 = ["0": 5, "1": 4, "2": 8]
let dict2 = ["0": 3, "1": 9, "2": 7]
let array = [dict0, dict1, dict2]

let keys = ["ant", "bee", "spider"]
let keysIndexedDictionary = Dictionary(uniqueKeysWithValues: keys.enumerated().map { (String($0), $1) })

let mappedArray = array.map { dic -> [String : Int] in
    // I wish this can be shortened using $ notation
    let mappedTuples = dic.flatMap { [(keysIndexedDictionary[$0] ?? $0) : $1] }
    return Dictionary(uniqueKeysWithValues: mappedTuples)
}
nayem
  • 7,285
  • 1
  • 33
  • 51
  • If you happen to have ___duplicate___ entries in the keys array, you will have to consider [this](https://stackoverflow.com/a/52743080/3687801). Or maybe you can eliminate that possibility in the first place by making keys collection a `Set` instead of `Array`, but you'll lose the order of the elements in the collection as `Set` in unordered. – nayem Nov 28 '19 at 06:17