如何在swift 2.1中从对象数组创建字典?

时间:2015-11-03 17:01:14

标签: ios arrays swift dictionary

我有一个类型" drugList"的数组,它们来自一个结构" DrugsLibrary":

seznamDnu.add(new ListDays(prvniDenMesice.plusDays(i).format(DateTimeFormatter.ofPattern("EE dd"))));}

我的数据模型使用此函数初始化:

struct DrugsLibrary {
    var drugName = ""
    var drugCategory = ""
    var drugSubCategory = ""
}

 var drugList = [DrugsLibrary]()
 //This is the dictionary i'm trying to build:
 var dictionary = ["": [""," "]]

我的问题是我试图从drugList创建一个字典,其中键是drugSubCategory,值是药物名称。如果此子类别中有多种药物,则该值应为数组 例如,在这个例子中,字典看起来应该是这样的:

  func createDrugsList() {        
        var drug1 = DrugsLibrary()
        drug1.drugName = "drug1"
        drug1.drugCategory = "Antibiotics"
        drug1.drugSubCategory = "Penicillins"
        self.drugList.append(drug1)  

        var drug2 = DrugsLibrary()
        drug2.drugName = "drug2"
        drug2.drugCategory = "Antibiotics"
        drug2.drugSubCategory = "Penicillins"
        self.drugList.append(drug2) 

        var drug3 = DrugsLibrary()
        drug3.drugName = "drug2"
        drug3.drugCategory = "Antibiotics"
        drug3.drugSubCategory = "Macrolides"
        self.drugList.append(drug3) 
}

我试过这个方法:

 dictionary = [
     "Penicillins": ["drug1","drug2"]
     "Macrolides": ["drug3"]
    ] 

这给了这样的字典,并且它无法将药物2附加到" Penicllins":

   for item in drugList {
        dictionary["\(item.drugSubCategory)"] = ["\(item.drugName)"]            
    }

所以我尝试使用此方法将项目附加到字典中,但它没有附加任何内容,因为数据模型中没有关键字 dictionary = [ "Penicillins": ["drug1"] "Macrolides": ["drug3"] ] 的常见项目:

""

任何人都知道将drug2追加到词典中的方法吗?

我很感激在这件事上有任何帮助或建议。

3 个答案:

答案 0 :(得分:2)

您需要创建一个新数组,其中包含前一个数组的内容以及新项目或新数组以及新项目,并将其分配给您的字典:

for item in drugList {
    dictionary[item.drugSubCategory] = dictionary[item.drugSubCategory] ?? [] + [item.drugName]
}

答案 1 :(得分:1)

在Playground中复制此内容可能会帮助您更好地理解词典:

 import UIKit

var str = "Hello, playground"


struct DrugsLibrary {
    var drugName = ""
    var drugCategory = ""
    var drugSubCategory = ""
}

var drugList = [DrugsLibrary]()
//This is the dictionary i'm trying to build:
var dictionary = ["":""]

func createDrugsList() {
    var drug1 = DrugsLibrary()
    drug1.drugName = "drug1"
    drug1.drugCategory = "Antibiotics"
    drug1.drugSubCategory = "Penicillins"
    drugList.append(drug1)

    var drug2 = DrugsLibrary()
    drug2.drugName = "drug2"
    drug2.drugCategory = "Antibiotics"
    drug2.drugSubCategory = "Penicillins"
    drugList.append(drug2)

    var drug3 = DrugsLibrary()
    drug3.drugName = "drug2"
    drug3.drugCategory = "Antibiotics"
    drug3.drugSubCategory = "Macrolides"
    drugList.append(drug3)
}

createDrugsList()
print(drugList)


func addItemsToDict() {
for i in drugList {

    dictionary["item \(i.drugSubCategory)"] = "\(i.drugName)"

}
}
addItemsToDict()

print(dictionary)

答案 2 :(得分:1)

您可以在此处使用.filterSet以及let categories = Set(drugList.map{$0.drugSubCategory}) 。首先,您需要一个字典键数组,但没有重复项(因此使用一组)

for category in categories {
    let filteredByCategory = drugList.filter {$0.drugSubCategory == category}
    let extractDrugNames = filteredByCategory.map{$0.drugName}
    dictionary[category] = extractDrugNames
}

然后,您想迭代这些独特的类别,找到该类别中的每种药物并提取其名称:

for

删除dictionary循环,如果需要更多的Swifty-ness,则留给读者练习;)。

我有两个不相关的观察结果:

1)不确定您是否将其视为示例,但您已使用空字符串初始化var dictionary = [String:[String]]() 。除非您想要空字符串条目,否则将来必须删除它们。你最好用正确的类型初始化一个空字典:

self.

2)您无需使用dictionary来访问实例变量。您的代码非常简单,self的范围非常明显(请参阅 <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawVisualization); function drawVisualization() { // Some raw data (not necessarily accurate) var data = google.visualization.arrayToDataTable([ ['Month', 'Bolivia', 'Ecuador', 'Madagascar', 'Papua New Guinea', 'Rwanda', 'Average'], ['2004/05', 165, 938, 522, 998, 450, 614.6], ['2005/06', 135, 1120, 599, 1268, 288, 682], ['2006/07', 157, 1167, 587, 807, 397, 623], ['2007/08', 139, 1110, 615, 968, 215, 609.4], ['2008/09', 136, 691, 629, 1026, 366, 569.6] ]); var options = { title : 'Monthly Coffee Production by Country', vAxis: {title: 'Cups'}, hAxis: {title: 'Month'}, seriesType: 'bars', series: {5: {type: 'line'}} }; var chart = new google.visualization.ComboChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> <div id="chart_div" style="width: 900px; height: 500px;"></div>

import matplotlib.pyplot as plt plt.plot(*result.T) 的优秀文章