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]]
In this case, Dictionary(grouping:by:)
creates a Dictionary
of type [Character : [(key: String, value: Int)]]
. So the values are an array of (key: String, value: Int)
tuples.
Use .mapValues()
to convert the Array of (key: String, value: Int)
tuples into a Dictionary
by calling Dictionary(uniqueKeysWithValues)
with the array:
var displayValues = ["volume_1": 1, "price_2": 6, "price_1": 2, "stock_1": 3, "volume_2": 5, "stock_2": 7]
let groupValues = Dictionary(grouping: displayValues) { String($0.key.suffix(1)) }
.mapValues { Dictionary(uniqueKeysWithValues: $0) }
print(groupValues)
Result:
["1": ["stock_1": 3, "price_1": 2, "volume_1": 1], "2": ["volume_2": 5, "stock_2": 7, "price_2": 6]]
Note:
To avoid a force unwrap (which will crash if you have an empty String
as a key), I used String($0.key.suffix(1))
instead of $0.key.last!
. This will make the final dictionary [String : [String : Int]]
which can be conveniently indexed with a String
.
Thanks to @LeoDabus for this suggestion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.