We also have the option of creating dictionaries that are initialized with elements. In a dictionary, an element refers to a single key-value pair.
To create a populated dictionary, we will use dictionary literal syntax. A dictionary literal is a collection of comma-separated key-value pairs.
The syntax to create a populated dictionary looks like this:
var dictionaryName: [KeyType: ValueType] = [
Key1: Value1,
Key2: Value2,
Key3: Value3
]
- There is a type annotation for both the key and the value.
- Each key is unique.
- The keys and values must belong to their specified type.
- The key and the value are separated by a colon
:
. - All of the elements are contained within brackets
[]
. - Each key-value pair is separated by a comma
,
.
Let’s create a dictionary called fruitStand
that stores information about fruit stock:
var fruitStand: [String: Int] = [ "Apples": 12, "Bananas": 20 ]
- The keys are type
String
and the values are typeInt
. - There are two key-value pairs in our dictionary.
- One pair has a key of
"Apples"
with a value of12
. - The other pair has a key of
"Bananas"
and a value of20
.
If we use print()
to output the value of fruitStand
, we could get the following result:
["Bananas": 20, "Apples": 12]
Dictionaries are unordered- when we use print()
to output a dictionary, the order of the elements may not appear in the order they were added in.
Instructions
Declare a dictionary variable named roleModels
that contains String
type keys and String
type values using dictionary literal syntax.
Do not add values to this dictionary yet.
This code will be modified in the next step so that the dictionary is initialized with values inside of it.
Inside roleModels
, add the following key-value pairs:
"Mr. Rogers"
:"Fred McFeely Rogers"
"The Crocodile Hunter"
:"Stephen Robert Irwin"
"Bill Nye the Science Guy"
:"William Sanford Nye"
Use print()
to output the content of roleModels
.
Run the program a few times. Did the order in which the elements appear change?