Home > Enterprise >  Create a dictionary with values from another dictionary
Create a dictionary with values from another dictionary

Time:11-02

Here's the challenge: Imagine you're working on an electronic diary application. Create a dictionary where the key will be the student's name and the value will be another 3-element dictionary containing the subject name and grade.

var items = ["Mathematics": 4, "Literature": 5, "Chemistry": 3]
var diary = ["Mike": items]
print(diary)

I did like this. Show how to initialize a dictionary in another dictionary?

CodePudding user response:

Something like that will do:

let diary: [String: [String: Int]]

var items = ["Mathematics": 4, "Literature": 5, "Chemistry": 3]

diary["Mike"] = items

print(diary)

CodePudding user response:

To change a value inside the dictionary use:

var items = ["Mathematics": 4, "Literature": 5, "Chemistry": 3]
var diary = ["Mike": items]
print(diary)

// In other way, if you need to change only the grade or add a new discipline you could.

diary["Mike"]?["Mathematics"] = 10

print(diary)
  • Related