如何删除字典中元素的下划线及其后的字符

How to remove underscore and the characters after it of the elements in a Dictionary

我有一本看起来像这样的字典。

    ["price_2": 20.0, "stock_2": 100, "volume_2": "2L", "sku_2": 2, "volume_0": "1L", "sku_0": 1, "price_0": 10.0, "stock_0": 100]

我按最后一个字符对它们进行了分组。为了删除下划线和它后面的字符,我使用 key.droplast(2) 但是当下划线后面有更多字符时,这将不起作用,比如当一个键变成 volume_150.

    Code:
    let dict = Dictionary(grouping: displayValues) { String([=11=].key.suffix(1)) }.mapValues { 
    [=11=].reduce(into: [:]) { [=11=][.key.dropLast(2)] = .value } }


    Result:
    ["2":["price": 20.0, "stock": 100, "volume": "2L", "sku": 2], 
    "0": ["volume": "1L", "sku": 1, "price": 10.0, "stock": 100]]

如何删除下划线及其后的字符?

使用 .split(seperator: "_").first 按照您的要求获取密钥。

let yourDictionary =  ["price_2": 20.0, "stock_2": 100, "volume_2": "2L", "sku_2": 2, "volume_0": "1L", "sku_0": 1, "price_0": 10.0, "stock_0": 100] as [String : Any]

for key in yourDictionary.keys {
    let newKey = key.split(separator: "_").first
    print(newKey!)
}