Dictionaries
Dictionaries, also referred to as a key-value store, are associative containers that contain values referenced by keys.
var simpleDictionary = {"name": "John"}
In the code above, the key name
, while the value is "John"
You are also able to use other datatypees besides strings as keys:
var integerDictionary = {1: "John"}
var floatDictionary = {2.13: "Jane"}
var booleanDictionary = {true: "Sarah"}
Accessing Dictionaries
# Create Dictionaries
var simpleDictionary = {"name": "John"}
var integerDictionary = {1: "Jane"}
var floatDictionary = {2.13: "Josh"}
var booleanDictionary = {true: "Sarah"}
# Retrieve values
var getJohn = simpleDictionary["name"] # "John"
var getJane = integerDictionary[1] # "Jane"
var getJosh = floatDictionary[2.13] # "Josh"
var getJohn = booleanDictionary[true] # "Sarah"
# You can use dot notation if retrieving string keys
var getJohnAgain = simpleDictionary.name # "John"
Assigning Values to an Existing Key
var simpleDictionary = {"name": "John"}
# One way
simpleDictionary["name"] = "Jane"
# Another way
simpleDictionary.name = "Jane Doe"
Creating New Key-Value Pair
var simpleDictionary = {"name": "Jane"}
simpleDictionary["birthdate"] = "December 2020"
simpleDictionary.age = 0
Comparing Dictionaries key-value pairs
If you compare dictionaries with a comparison operator, you will return false even if the
dictionaries compared are exactly the same:
var simpleDictionary = {"name": "Jane"}
var sameDictionary = {"name": "Jane"}
if(simpleDictionary == sameDictionary):
# Block of code never runs
To get the desired results when coparing dictionaries, use the hash
method:
var simpleDictionary = {"name": "Jane"}
var sameDictionary = {"name": "Jane"}
if(simpleDictionary.hash() == sameDictionary.hash()):
# Block of code runs
Delete a key-value pair
To delete a key-value pair, use the erase
method:
var simpleDictionary = {"name": "Jane"}
simpleDictionary.erase("name")