kangarooChris
kangarooChris

Reputation: 768

fill dictionary with data

I want to fill the dictionary with data, so that it looks like this: 1:Apple 2:Banana 3:Lemon

Sorry, if this is too simple for probably most of you - I am just a beginner. Anyway, here is the code:

var listOfFruit = ["Apple", "Banana","Lemon"]
var key = [1,2,3]
var dictionary = [Int: [String]]()
func createDictionary(){

for index in key {
    dictionary[index] = []
    var listOfFruit = ["Apple", "Banana","Lemon"]
    for index1 in listOfFruit{
        dictionary[index]?.append(index1)
    }
}
}
print(dictionary)

The result of the above is "[:]\n" in my playground.

Upvotes: 0

Views: 67

Answers (3)

Ahmed Onawale
Ahmed Onawale

Reputation: 4050

var listOfFruit = ["Apple", "Banana","Lemon"]
var key = [1,2,3]
var dictionary = [Int: String]()

func createDictionary(){
    for (index, value) in key.enumerate() {
        dictionary[value] = listOfFruit[index]
    }
}

createDictionary()

print(dictionary)

Upvotes: 0

Michael Kohl
Michael Kohl

Reputation: 66837

A functional approach to creating your dictionary could look like this:

let dictionary = zip(listOfFruit, key).map { [$1: $0] }
print(dictionary)
// [[1: "Apple"], [2: "Banana"], [3: "Lemon"]]

Upvotes: 2

Shades
Shades

Reputation: 5616

let listOfFruit = ["Apple", "Banana","Lemon"]
let key = [1,2,3]
var dictionary = [Int: String]()
func createDictionary(){
    var i = 0
    while i < listOfFruit.count {
        dictionary[key[i]] = listOfFruit[i]
        i += 1
    }
}
createDictionary()
print(dictionary)

Note the change of the line:

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

to:

var dictionary = [Int: String]()

and the use of the variable i to get the same index from each array.

Upvotes: 0

Related Questions