简体   繁体   English

如何在swift中比较两个词典然后在新词典中附加任何相似之处?

[英]How do i compare two dictionaries in swift and then append any similarities to a new dictionary?

i know this might seem like a confusing question so here's my scenario... I have two dictionaries and i need to organise them into one dictionary where the keys from both of the initial 2 dictionaries share the same values from the keys that are the same from the starting 2 dictionaries. 我知道这可能看起来像一个令人困惑的问题,所以这是我的场景...我有两个字典,我需要将它们组织成一个字典,其中来自两个最初的2个字典的键共享来自相同键的相同值从2开头的词典开始。 Example: 例:

var dict1 = [1: "fruit", 2: "vegetable", 3: "meat"]
var dict2 = [2: "carrot", 3: "steak", 1: "apple", 3: "pork"] 
var newDict = [1: ["fruit": ["apple"]], 2: ["vegetable": ["carrot"]], 3: ["meat": ["steak, pork"]]]

So its organised where each category (fruit, veg, meat) has a unique id (Int), and in that category is an array of values appropriate for that category. 因此,它组织了每个类别(水果,蔬菜,肉类)具有唯一ID(Int),并且在该类别中是适合该类别的一系列值。 The end result is that i'm hoping to populate a table view with this data using the category's as section headers and the array of values for that sections data. 最终的结果是,我希望使用类别作为节标题和该节数据的值数组来填充包含此数据的表视图。

Any help is much appreciated. 任何帮助深表感谢。 Thanks :) 谢谢 :)

As I said in the comment, your second dictionary has duplicate keys, so it's not valid Swift. 正如我在评论中所说,你的第二本字典有重复的键,所以它不是Swift的有效。

Assuming you solve the duplicate key issue by replacing the duplicate with a new one, unique this time, here is a quick algorithm almost achieving what you want. 假设您通过用新的替换副本来解决重复键问题,这次是唯一的,这是一个快速算法,几乎达到了你想要的。

let dict1 = [1: "fruit", 2: "vegetable", 3: "meat"]
let dict2 = [2: "carrot", 3: "steak", 1: "apple", 4: "pork"]

var newDict = [Int:[String:[String]]]()

for category in dict1 {
    if let existingCat = newDict[category.key] {

    } else {
        let newCat = [category.value: [dict2[category.key]!]]
        newDict[category.key] = newCat
    }
}

print (newDict)

It won't give you the list of products you want though, so I've changed your input data types to something more suitable (I'm not saying it's optimal, but it works): 它不会给你你想要的产品列表,所以我把你的输入数据类型更改为更合适的东西(我不是说它是最优的,但是它有效):

let input1 = [(1, "fruit"), (2, "vegetable"), (3, "meat")]
let input2 = [(2, "carrot"), (3, "steak"), (1, "apple"), (3, "pork")]

var newDict = [Int:[String:[String]]]()

for category in input1 {
    newDict[category.0] = [category.1:[]]
}

for meal in input2 {
    if let existingCat = newDict[meal.0]?.first {
        newDict[meal.0] = [existingCat.key: existingCat.value + [meal.1]]
    }
}

print (newDict)

At the end newDict prints: 最后newDict打印:

[2: ["vegetable": ["carrot"]], 3: ["meat": ["steak", "pork"]], 1: ["fruit": ["apple"]]]

Your code does not compile 您的代码无法编译

As @Bogdan Farca noted in the comments your second dictionary won't compile because of duplicate key 正如@Bogdan Farca在评论中指出的那样,由于重复键,你的第二本字典将无法编译

let dict2 = [2: "carrot", 3: "steak", 1: "apple", 3: "pork"]

在此输入图像描述

A better way to represent the information of dict2 is using the food name as key and the category ID as value 表示dict2信息的更好方法是使用食物名称作为key ,使用类别ID作为value

let dict2 = ["carrot" : 2,"steak": 2,"apple": 1, "pork":3]

I am assuming the food names to be unique. 我假设食物名称是独特的。

Better names 更好的名字

In order to make the code more readable we should also use better names so 为了使代码更具可读性,我们也应该使用更好的名称

let categories = [1: "fruit", 2: "vegetable", 3: "meat"]
let foods = ["carrot" : 2, "steak": 3, "apple": 1, "pork":3]

Using a Model 使用模型

We can finally focus on the solution. 我们终于可以专注于解决方案了。 You want as output something like this [Int : Dictionary<String, Array<String>>] 你想要像这样的输出[Int : Dictionary<String, Array<String>>]

It's a complex combination of dictionaries/arrays, why don't you simply use a model value? 它是字典/数组的复杂组合,为什么不简单地使用模型值?

struct FoodCategory {
    let categoryID: Int
    let categoryName: String
    let foods: [String]
}

Now you can just write 现在你可以写

let foodCategories = categories.map { cat -> FoodCategory in
    let foodNames = foods.filter { $0.value == cat.key }.map { $0.0 }
    return FoodCategory(categoryID: cat.key, categoryName: cat.value, foods: foodNames )
}

And this is the result 这就是结果

[
    FoodCategory(categoryID: 2, categoryName: "vegetable", foods: ["carrot"]),
    FoodCategory(categoryID: 3, categoryName: "meat", foods: ["pork", "steak"]),
    FoodCategory(categoryID: 1, categoryName: "fruit", foods: ["apple"])
]

If you correct your dictionaries to: 如果你更正你的词典:

let dict1 = [1: "fruit", 2: "vegetable", 3: "meat"]
var dict2 = [2: ["carrot"], 1: ["apple"], 3: ["pork", "steak"]]

you could reduce it with 你可以减少它

let result = dict1.keys.reduce([Int: [String: [String]]]()) { (result, key) in
    var result = result
    result.updateValue([dict1[key]!: dict2[key] ?? []], forKey: key)
    return result
}

which would result in [2: ["vegetable": ["carrot"]], 3: ["meat": ["pork", "steak"]], 1: ["fruit": ["apple"]]] 这将导致[2: ["vegetable": ["carrot"]], 3: ["meat": ["pork", "steak"]], 1: ["fruit": ["apple"]]]

This may be help for you 这可能对你有所帮助

 var dict1 = [(0, ["sender": "user1", "time": NSDate(), "mId": "as2f2ASf"]), (1, ["sender": "user1", "time": NSDate(), "mId": "Sjf82FsJ"])]

 var dict2 = [(0, ["sender": "user2", "time": NSDate(), "mId": "J2fAS92D"]), (1, ["sender": "user2", "time": NSDate(), "mId": "Sjf82FsJ"])]


var dict3 = [[0: ["sender": "user1", "time": NSDate(), "mId": "as2f2ASf"]], [1: ["sender": "user1", "time": NSDate(), "mId": "Sjf82FsJ"]]]for (_,value1) in dict1 {


 if let mld1 = value1["mId"] {
for(_,value2) in dict2 {
  if let mld2 = value2["mId"] {
    if mld1 == mld2 {
      println("Found diff")
    }
  }
}
 }
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM