字典

字典,也称为键值存储,是包含键引用的值的关联容器。

  1. var simpleDictionary = {"name": "John"}

在上面的代码中, key name,而 value 是”John”
除了字符串之外,您还可以使用其他数据类型作为键:

  1. var integerDictionary = {1: "John"}
  2. var floatDictionary = {2.13: "Jane"}
  3. var booleanDictionary = {true: "Sarah"}

访问字典

  1. # Create Dictionaries
  2. var simpleDictionary = {"name": "John"}
  3. var integerDictionary = {1: "Jane"}
  4. var floatDictionary = {2.13: "Josh"}
  5. var booleanDictionary = {true: "Sarah"}
  6. # Retrieve values
  7. var getJohn = simpleDictionary["name"] # "John"
  8. var getJane = integerDictionary[1] # "Jane"
  9. var getJosh = floatDictionary[2.13] # "Josh"
  10. var getJohn = booleanDictionary[true] # "Sarah"
  11. # You can use dot notation if retrieving string keys
  12. var getJohnAgain = simpleDictionary.name # "John"

将值分配给现有键

  1. var simpleDictionary = {"name": "John"}
  2. # One way
  3. simpleDictionary["name"] = "Jane"
  4. # Another way
  5. simpleDictionary.name = "Jane Doe"

创建新的键值对

  1. var simpleDictionary = {"name": "Jane"}
  2. simpleDictionary["birthdate"] = "December 2020"
  3. simpleDictionary.age = 0

比较字典键值对

如果用比较运算符比较字典,即使比较的字典完全相同,也会返回 false:

  1. var simpleDictionary = {"name": "Jane"}
  2. var sameDictionary = {"name": "Jane"}
  3. if(simpleDictionary == sameDictionary):
  4. # Block of code never runs

要在 coparing 字典时获得所需的结果,请使用以下hash方法:

  1. var simpleDictionary = {"name": "Jane"}
  2. var sameDictionary = {"name": "Jane"}
  3. if(simpleDictionary.hash() == sameDictionary.hash()):
  4. # Block of code runs

删除键值对

要删除键值对,请使用以下erase方法:

  1. var simpleDictionary = {"name": "Jane"}
  2. simpleDictionary.erase("name")