字典
字典,也称为键值存储,是包含键引用的值的关联容器。
var simpleDictionary = {"name": "John"}
在上面的代码中, key name,而 value 是”John”
除了字符串之外,您还可以使用其他数据类型作为键:
var integerDictionary = {1: "John"}var floatDictionary = {2.13: "Jane"}var booleanDictionary = {true: "Sarah"}
访问字典
# Create Dictionariesvar simpleDictionary = {"name": "John"}var integerDictionary = {1: "Jane"}var floatDictionary = {2.13: "Josh"}var booleanDictionary = {true: "Sarah"}# Retrieve valuesvar 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 keysvar getJohnAgain = simpleDictionary.name # "John"
将值分配给现有键
var simpleDictionary = {"name": "John"}# One waysimpleDictionary["name"] = "Jane"# Another waysimpleDictionary.name = "Jane Doe"
创建新的键值对
var simpleDictionary = {"name": "Jane"}simpleDictionary["birthdate"] = "December 2020"simpleDictionary.age = 0
比较字典键值对
如果用比较运算符比较字典,即使比较的字典完全相同,也会返回 false:
var simpleDictionary = {"name": "Jane"}var sameDictionary = {"name": "Jane"}if(simpleDictionary == sameDictionary):# Block of code never runs
要在 coparing 字典时获得所需的结果,请使用以下hash方法:
var simpleDictionary = {"name": "Jane"}var sameDictionary = {"name": "Jane"}if(simpleDictionary.hash() == sameDictionary.hash()):# Block of code runs
删除键值对
要删除键值对,请使用以下erase方法:
var simpleDictionary = {"name": "Jane"}simpleDictionary.erase("name")
