我有[Int:[String:String]]
类型的字典
示例:
[1546696330:[“符号”:“ ETH”,“数量”:“ 1.0”],1546531017:[“符号”:“ ETH”,“数量”:“ 1.0”],1546531031:[“符号” :“ XRP”,“金额”:“ 200.0”]]
如您所见,我有两个重复的字典,键为symbol
,值为ETH
。我需要删除所有值并保留最小值(整数)的代码。
预期结果:
[1546531017:[“符号”:“ ETH”,“金额”:“ 1.0”],1546531031:[“符号”:“ XRP”,“金额”:“ 200.0”]]
1546531017 < 1546696330
答案 0 :(得分:3)
@Larme在评论中描述的算法是解决此问题的直接方法。
创建一个[String:Int]
字典,该字典表示要保留的原始字典中的值。 键是符号,而 value 是您要保留的Int
。
然后使用该字典通过使用keep
的值从原始字典中选择条目来构造最终的字典。
代码如下:
// original dictionary
let dict: [Int:[String:String]] = [1546696330: ["symbol": "ETH", "amount": "1.0"], 1546531017: ["symbol": "ETH", "amount": "1.0"], 1546531031: ["symbol": "XRP", "amount": "200.0"]]
// Dictionary mapping symbol to Int of values we want to keep
var keep = [String:Int]()
// Loop on original dictionary deciding on whether to keep this symbol
// based on how its Int compares to the one we've already kept
for (key, value) in dict {
guard let symbol = value["symbol"] else { continue }
if let ekey = keep[symbol] {
// We already have this one, so keep the minimum of the two
keep[symbol] = min(key, ekey)
} else {
keep[symbol] = key
}
}
// Show the keep dictionary
print(keep)
["XRP": 1546531031, "ETH": 1546531017]
// The final dictionary
var dict2 = [Int:[String:String]]()
// Fill the final dictionary based upon the values we chose to keep
for value in keep.values {
dict2[value] = dict[value]
}
// Show the final result
print(dict2)
[1546531031: ["amount": "200.0", "symbol": "XRP"], 1546531017: ["amount": "1.0", "symbol": "ETH"]]
使用keep
创建reduce(into:)
:
如果要使用reduce(into:)
创建keep
字典来降低可读性,则需要更多Swifty:
let keep: [String:Int] = dict.reduce(into: [:]) {
guard let symbol = $1.value["symbol"] else { return }
$0[symbol] = min($0[symbol, default: $1.key], $1.key)
}
使用filter()
创建最终字典:
或者,您可以像这样通过过滤原始字典来在一行中创建最终字典:
let dict2 = dict.filter { keep.values.contains($0.key) }
答案 1 :(得分:1)
这将删除具有较大int值的重复项
let dict:[Int:[String:String]] = [ 1546531017: ["symbol": "ETH", "amount": "1.0"], 1546531031: ["symbol": "XRP", "amount": "200.0"],1546696330: ["symbol": "ETH", "amount": "1.0"]]
var dict2:[Int:[String:String]] = [:]
dict.forEach({ (key, value) in
if let item = dict2.first(where: {value["symbol"] == $1["symbol"]}) {
if (key < item.key) {
dict2[item.key] = nil
dict2[key] = value
}
} else {
dict2[key] = value
}
})