I have a dictionary that I want to group by the last character of the keys. This is the dictionary:
var displayValues = ["volume_1": 1, "price_2": 6, "price_1": 2, "stock_1": 3, "volume_2": 5, "stock_2": 7]
This is the code that I used in order to group them
let groupValues = Dictionary(grouping: displayValues) { $0.key.last! }
print(groupValues)
This is the result of this code
["2": [(key: "price_2", value: 6), (key: "volume_2", value: 5), (key: "stock_2", value: 7)], "1": [(key: "volume_1", value: 1), (key: "price_1", value: 2), (key: "stock_1", value: 3)]]
The grouping is correct, however, how do I remove the words key and value from the dictionary so that it will display the following?
[
"2": ["price_2": 6, "volume_2" : 5, "stock_2": 7],
"1": ["volume_1": 1, "price_1": 2, "stock_1": 3]
]
You are almost there !!
now You have key as you wanted and value as array of tuple
You can convert array of tuple into dictionary with new reduce(into:)
full code would be
var displayValues = ["volume_1": 1, "price_2": 6, "price_1": 2, "stock_1": 3, "volume_2": 5, "stock_2": 7];
let dict = Dictionary(grouping: displayValues) { $0.key.suffix(1)}
let final = dict. mapValues { value in
return value.reduce(into: [:]) { $0[$1.key] = $1.value }
}
print(final)
Output :
["2": ["price_2": 6, "volume_2": 5, "stock_2": 7], "1": ["price_1": 2, "stock_1": 3, "volume_1": 1]]
If 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