Janmejay Yadav
Janmejay Yadav

Reputation: 19

can i sum of values that has the same key in dictionary

I have a dictionary like this :

let dic: KeyValuePairs = ["foo":2,"bar":3,"bat":5, "foo":5,"bat":7,"bar":5]

I want the sum of values that has the same key.

The output should look like this:

["foo":7, "bar":8, "bat":12]

Upvotes: 0

Views: 71

Answers (1)

vadian
vadian

Reputation: 285160

KeyValuePairs responds to reduce so you can do this

let dic: KeyValuePairs = ["foo":2,"bar":3,"bat":5, "foo":5,"bat":7,"bar":5]

let result : [String:Int] = dic.reduce(into: [:]) { (current, new) in
    current[new.key] = new.value + (current[new.key] ?? 0)
}

Upvotes: 1

Related Questions