2

I have a array of dictionaries which contains same key but different values. I want to merge these dictionaries and add all the values of same keys just like below:

var arrayofDict = [["2019":"A"],["2019":"B"],["2019":"C"],["2018":"A"],["2018":"c"],["2017":"A"],["2017":"B"],["2017":"C"],["2016":"A"],["2015":"A"],["2015":"B"]]

expected result as an Array like:

   var newDict = [["2019":["A","B","C"]],["2018":["A","C"]],["2017":["A","B","C"]],["2016":["A"]],["2015":["A","B"]]]
2
  • 1
    "I have a array of dictionaries which contains same key but different values." I'm curious: Where did you get it from? Do you have control over that data? Commented Jan 31, 2020 at 16:35
  • 2
    Your expected result is actually an array Commented Jan 31, 2020 at 16:40

2 Answers 2

4

This shows how to build a single dictionary. Your "expected result" is an array. Is this what you really expected or did you want an array?

You can iterate the dictionary items and build up the dictionary entries:

var arrayofDict = [["2019":"A"],["2019":"B"],["2019":"C"],["2018":"A"],["2018":"c"],["2017":"A"],["2017":"B"],["2017":"C"],["2016":"A"],["2015":"A"],["2015":"B"]]

var result = [String : [String]]()
for dict in arrayofDict {
    for (key, value) in dict {
        result[key, default: []].append(value)
    }
}

print(result)
["2016": ["A"], "2018": ["A", "c"], "2015": ["A", "B"], "2019": ["A", "B", "C"], "2017": ["A", "B", "C"]]

Or, if you want an array:

let result2 = result.map { [$0.key: $0.value] }
print(result2)
[["2015": ["A", "B"]], ["2016": ["A"]], ["2019": ["A", "B", "C"]], ["2018": ["A", "c"]], ["2017": ["A", "B", "C"]]]
Sign up to request clarification or add additional context in comments.

2 Comments

How to sort this in descending order of the year? and also sort values too? @vacawama
let result2 = result.map { [$0.key: $0.value.sorted()] }; let result3 = result2.sorted(by: { $0.first!.key > $1.first!.key } )
0

as @vacawama in more functional way

let result = arrayofDict.reduce(into: [String:[String]]()) { (acc, d) in
    for key in d.keys {
        // don't worry to force unwrap d[key], if key exist, the value is not nil
        acc[key, default: []].append(d[key]!)
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.