I have the following dictionary:
let dict = ["key1": "v1", "key2": "v1", "key3": "v2"]
I want to swap the values for keys so that the result to be:
result = ["v1": ["key1", "key2"], "v2": ["key3"]]
How can I do this without using for
loops (i.e. in a functional way)?
In Swift 4, Dictionary
has the init(_:uniquingKeysWith:)
initializer that should serve well here.
let d = [1 : "one", 2 : "two", 3 : "three", 30: "three"]
let e = Dictionary(d.map({ ($1, [$0]) }), uniquingKeysWith: {
(old, new) in old + new
})
If you did not have duplicate values in the original dict that needed to be combined, this would be even simpler (using another new initializer):
let d = [1 : "one", 2 : "two", 3 : "three"]
let e = Dictionary(uniqueKeysWithValues: d.map({ ($1, $0) }))
You can use grouping initializer in Swift 4:
let dict = ["key1": "v1", "key2": "v1", "key3": "v2"]
let result = Dictionary(grouping: dict.keys.sorted(), by: { dict[$0]! })
Two notes:
.sorted()
if the order of keys in resulting arrays is not important.$0
parameterIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With