筛选/识别具有匹配值的字典键 [英] filter/identify dictionary keys that have matching values

查看:79
本文介绍了筛选/识别具有匹配值的字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定是否需要减少,排序,过滤或使用较新的独特方法.我什至尝试了Equatable解决方案.

Not sure if I need reduce, sorting, filtering or using the newer unique methods. I've even tried Equatable solutions.

我需要自动识别具有匹配值的键,并仅采用那些键并将其放入新的字典或数组中.

I need to auto-identify keys that have matching values and take only those keys and put them into a new dictionary or array.

var userDB: [String:Any] = ["userID1":"gameIDa", "userID2":"gameIDa", "userID3":"gameIDc", "userID4":"gameIDd", "userID5":"gameIDe"]


如您所见,只有这两个ID具有相同的gameIDa值.我需要此结果的输出.


As you can see only these two IDs have the same value of gameIDa. I need output of this result.

// [userID1, userID2]

谢谢

推荐答案

您可以使用

You can use Dictionary(grouping:by:) to achieve this easily and then reduce it to a dictionary which contains only entries with multiple values.

var userDB: [String: String] = ["userID1":"gameIDa", "userID2":"gameIDb", "userID3":"gameIDc", "userID4":"gameIDa", "userID5":"gameIDe"]

let dict = Dictionary(grouping: userDB.keys) { userDB[$0] ?? "" }.reduce(into: [String:[String]](), { (result, element) in
    if element.value.count > 1 {
        result[element.key] = element.value
    }
})

dict

dict

["gameIDa":["userID1","userID4"]]

["gameIDa": ["userID1", "userID4"]]

这篇关于筛选/识别具有匹配值的字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆