Rami Ammoun
Rami Ammoun

Reputation: 857

How do I create a dictionary from an array of objects in swift 2.1?

I have an array of type "drugList", and they are derived from a struct "DrugsLibrary":

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

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

My data model is initialized using this function:

  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) 
}

my problem is that i'm trying to create a dictionary from the drugList where the key is the drugSubCategory and the value is the drug name. The value should be an array if there are several drugs in this subcategory for example, the dictionary should look something like this for this example:

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

I tried this method:

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

this gave a dictionary like this, and it couldn't append drug2 to "Penicllins":

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

So I tried to append the items into the dictionary using this method but it didn't append anything because there were no common items with the key "" in the data model:

for item in drugList {
  names1[item1.drugSubCategory]?.append(item1.drugName)  
  }

Anyone knows a way to append drug2 to the dictionary?

I would appreciate any help or suggestion in this matter.

Upvotes: 0

Views: 941

Answers (3)

Joseph Quigley
Joseph Quigley

Reputation: 346

You can use .map and .filter and Set to your advantage here. First you want an array of dictionary keys, but no duplicates (so use a set)

let categories = Set(drugList.map{$0.drugSubCategory})

Then you want to iterate over the unique categories and find every drug in that category and extract its name:

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

Removing the for loop, if more Swifty-ness is desired, is left as an exercise to the reader ;).

I have two unrelated observations:

1) Not sure if you meant it as an example or not, but you've initialized dictionary with empty strings. You'll have to remove those in the future unless you want an empty strings entry. You're better off initializing an empty dictionary with the correct types:

var dictionary = [String:[String]]()

2) You don't need to use self. to access an instance variable. Your code is simple enough that it's very obvious what the scope of dictionary is (see this great writeup on self from a Programmers's stack exchange post.

Upvotes: 1

helpMeCodeSwift
helpMeCodeSwift

Reputation: 93

Copy this in your Playground, might help you understand the Dictionaries better:

 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)

Upvotes: 1

Charles A.
Charles A.

Reputation: 11143

You need to create a new array containing the contents of the previous array plus the new item or a new array plus the new item, and assign this to your dictionary:

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

Upvotes: 2

Related Questions