Dictionary

包含键值对的内置数据结构。

描述

字典是关系容器,包含的值(Value)由唯一的键(Key)引用。添加新条目时,字典会保持插入顺序。在其他编程语言中,这种数据结构有时也称为哈希表或关联数组。

在大括号 {} 中放置用逗号分隔的一对对 键: 值 列表就可以定义字典。

字典的创建:

GDScriptC#

  1. var my_dict = {} # 创建空字典。
  2. var dict_variable_key = "Another key name"
  3. var dict_variable_value = "value2"
  4. var another_dict = {
  5. "Some key name": "value1",
  6. dict_variable_key: dict_variable_value,
  7. }
  8. var points_dict = {"White": 50, "Yellow": 75, "Orange": 100}
  9. # 备选 Lua 分隔语法。
  10. # 不需要在键周围加引号,但键名只能为字符串常量。
  11. # 另外,键名必须以字母或下划线开头。
  12. # 此处的 `some_key` 是字符串字面量,不是变量!
  13. another_dict = {
  14. some_key = 42,
  15. }
  1. var myDict = new Godot.Collections.Dictionary(); // 创建空字典。
  2. var pointsDict = new Godot.Collections.Dictionary
  3. {
  4. {"White", 50},
  5. {"Yellow", 75},
  6. {"Orange", 100}
  7. };

你可以通过键来访问字典中对应的值。上面的例子中,points_dict["White"] 会返回 50。你也可以写 points_dict.White,和前面的写法是等价的。不过如果用来访问字典的键不是固定字符串的话(例如数字或者变量),那么就只能使用方括号语法。

GDScriptC#

  1. @export_enum("White", "Yellow", "Orange") var my_color: String
  2. var points_dict = {"White": 50, "Yellow": 75, "Orange": 100}
  3. func _ready():
  4. # 不能使用点语法,因为 `my_color` 是变量。
  5. var points = points_dict[my_color]
  1. [Export(PropertyHint.Enum, "White,Yellow,Orange")]
  2. public string MyColor { get; set; }
  3. private Godot.Collections.Dictionary _pointsDict = new Godot.Collections.Dictionary
  4. {
  5. {"White", 50},
  6. {"Yellow", 75},
  7. {"Orange", 100}
  8. };
  9. public override void _Ready()
  10. {
  11. int points = (int)_pointsDict[MyColor];
  12. }

在上面的代码中,points 会被赋值为与 my_color 中选中的颜色相对应的值。

字典可以包含更复杂的数据:

GDScriptC#

  1. var my_dict = {
  2. "First Array": [1, 2, 3, 4] # 将 Array 赋给 String 键。
  3. }
  1. var myDict = new Godot.Collections.Dictionary
  2. {
  3. {"First Array", new Godot.Collections.Array{1, 2, 3, 4}}
  4. };

要往已有字典中添加键,请像已有键一样进行访问并赋值:

GDScriptC#

  1. var points_dict = {"White": 50, "Yellow": 75, "Orange": 100}
  2. points_dict["Blue"] = 150 # 将 "Blue" 添加为键,并将 150 赋为它的值。
  1. var pointsDict = new Godot.Collections.Dictionary
  2. {
  3. {"White", 50},
  4. {"Yellow", 75},
  5. {"Orange", 100}
  6. };
  7. pointsDict["Blue"] = 150; // 将 "Blue" 添加为键,并将 150 赋为它的值。

最后,同一个字典里可以包含不同类型的键和值:

GDScriptC#

  1. # 这是有效的字典。
  2. # 要访问下面的 "Nested value",请使用 `my_dict.sub_dict.sub_key` 或 `my_dict["sub_dict"]["sub_key"]`。
  3. # 索引风格可以按需混合使用。
  4. var my_dict = {
  5. "String Key": 5,
  6. 4: [1, 2, 3],
  7. 7: "Hello",
  8. "sub_dict": {"sub_key": "Nested value"},
  9. }
  1. // 这是有效的字典。
  2. // 要访问下面的 "Nested value",请使用 `((Godot.Collections.Dictionary)myDict["sub_dict"])["sub_key"]`。
  3. var myDict = new Godot.Collections.Dictionary {
  4. {"String Key", 5},
  5. {4, new Godot.Collections.Array{1,2,3}},
  6. {7, "Hello"},
  7. {"sub_dict", new Godot.Collections.Dictionary{{"sub_key", "Nested value"}}}
  8. };

字典中的键可以用 for 关键字进行遍历:

GDScriptC#

  1. var groceries = {"Orange": 20, "Apple": 2, "Banana": 4}
  2. for fruit in groceries:
  3. var amount = groceries[fruit]
  1. var groceries = new Godot.Collections.Dictionary{{"Orange", 20}, {"Apple", 2}, {"Banana", 4}};
  2. foreach (var (fruit, amount) in groceries)
  3. {
  4. // `fruit` 为键,`amount` 为值。
  5. }

注意:字典始终按引用传递。要获取字典的副本,能独立于原字典进行修改,请使用 duplicate

注意:**不支持**在遍历字典时清除元素,可能造成无法预知的行为。

备注

通过 C# 使用这个 API 时有显著的不同。详见 C# API 与 GDScript 的差异

教程

构造函数

Dictionary

Dictionary ( )

Dictionary

Dictionary ( Dictionary from )

方法

void

clear ( )

Dictionary

duplicate ( bool deep=false ) const

bool

erase ( Variant key )

Variant

find_key ( Variant value ) const

Variant

get ( Variant key, Variant default=null ) const

bool

has ( Variant key ) const

bool

has_all ( Array keys ) const

int

hash ( ) const

bool

is_empty ( ) const

bool

is_read_only ( ) const

Array

keys ( ) const

void

make_read_only ( )

void

merge ( Dictionary dictionary, bool overwrite=false )

int

size ( ) const

Array

values ( ) const

操作符

bool

operator != ( Dictionary right )

bool

operator == ( Dictionary right )

Variant

operator [] ( Variant key )


构造函数说明

Dictionary Dictionary ( )

构造空的 Dictionary


Dictionary Dictionary ( Dictionary from )

返回与 from 相同的字典。如果你需要该字典的副本,请使用 duplicate


方法说明

void clear ( )

清空该字典,移除其中的所有条目。


Dictionary duplicate ( bool deep=false ) const

创建并返回该字典的副本。如果 deeptrue,内部的 DictionaryArray 键和值也会被递归复制。


bool erase ( Variant key )

如果字典中存在与键对应的条目,则将其移除。如果给定的键 key 在字典中存在,则返回 true ,否则返回 false

注意:请勿在遍历字典时擦除条目。你可以改为遍历 keys 数组。


Variant find_key ( Variant value ) const

找到并返回关联值等于 value 的第一个键,如果没有找到,则返回 null

注意:null 也是有效的键。如果字典中包含这个键,则 find_key 可能会给出误导性的结果。


Variant get ( Variant key, Variant default=null ) const

返回该字典中与给定的键 key 对应的值。如果 key 不存在,则返回 default,如果省略了该参数则返回 null


bool has ( Variant key ) const

如果该字典包含给定的键 key,则返回 true

GDScriptC#

  1. var my_dict = {
  2. "Godot" : 4,
  3. 210 : null,
  4. }
  5. print(my_dict.has("Godot")) # 输出 true
  6. print(my_dict.has(210)) # 输出 true
  7. print(my_dict.has(4)) # 输出 false
  1. var myDict = new Godot.Collections.Dictionary
  2. {
  3. { "Godot", 4 },
  4. { 210, default },
  5. };
  6. GD.Print(myDict.ContainsKey("Godot")); // 输出 true
  7. GD.Print(myDict.ContainsKey(210)); // 输出 true
  8. GD.Print(myDict.ContainsKey(4)); // 输出 false

在 GDScript 中等价于 in 运算符:

  1. if "Godot" in {"Godot": 4}:
  2. print("这个键存在!") # 会进行输出。

注意:只要键 key 存在,该方法就会返回 true,即便这个键对应的值为 null


bool has_all ( Array keys ) const

如果该字典包含给定数组 keys 中的所有键,则返回 true

  1. var data = {"width" : 10, "height" : 20}
  2. data.has_all(["height", "width"]) # 返回 true

int hash ( ) const

返回代表该字典内容的 32 位整数哈希值。

GDScriptC#

  1. var dict1 = {"A": 10, "B": 2}
  2. var dict2 = {"A": 10, "B": 2}
  3. print(dict1.hash() == dict2.hash()) # 输出 true
  1. var dict1 = new Godot.Collections.Dictionary{{"A", 10}, {"B", 2}};
  2. var dict2 = new Godot.Collections.Dictionary{{"A", 10}, {"B", 2}};
  3. // Godot.Collections.Dictionary 没有 Hash() 方法。请改用 GD.Hash()。
  4. GD.Print(GD.Hash(dict1) == GD.Hash(dict2)); // 输出 true

注意:如果两个字典条目相同,但顺序不同,则哈希值也不同。

注意:哈希值相同的字典不保证相同,因为可能存在哈希碰撞。相对地,哈希值不同的字典保证不同。


bool is_empty ( ) const

如果该字典为空(大小为 0),则返回 true。另见 size


bool is_read_only ( ) const

如果该字典是只读的,则返回 true 。见 make_read_only。用 const 关键字声明的字典自动只读。


Array keys ( ) const

返回该字典中的键列表。


void make_read_only ( )

使该字典只读,即禁用字典内容的修改。不适用于嵌套内容,例如内嵌字典的内容。


void merge ( Dictionary dictionary, bool overwrite=false )

dictionary 中的条目添加到该字典中。默认情况下,不会复制重复的键,除非 overwritetrue

GDScriptC#

  1. var dict = { "item": "sword", "quantity": 2 }
  2. var other_dict = { "quantity": 15, "color": "silver" }
  3. # 默认情况下禁用覆盖已有键。
  4. dict.merge(other_dict)
  5. print(dict) # { "item": "sword", "quantity": 2, "color": "silver" }
  6. # 启用覆盖已有键。
  7. dict.merge(other_dict, true)
  8. print(dict) # { "item": "sword", "quantity": 15, "color": "silver" }
  1. var dict = new Godot.Collections.Dictionary
  2. {
  3. ["item"] = "sword",
  4. ["quantity"] = 2,
  5. };
  6. var otherDict = new Godot.Collections.Dictionary
  7. {
  8. ["quantity"] = 15,
  9. ["color"] = "silver",
  10. };
  11. // 默认情况下禁用覆盖已有键。
  12. dict.Merge(otherDict);
  13. GD.Print(dict); // { "item": "sword", "quantity": 2, "color": "silver" }
  14. // 启用覆盖已有键。
  15. dict.Merge(otherDict, true);
  16. GD.Print(dict); // { "item": "sword", "quantity": 15, "color": "silver" }

注意:merge 是递归的。嵌套的字典是否可被视为键可以被覆盖,具体取决于 overwrite 的值,但它们永远不会被合并在一起。


int size ( ) const

返回该字典中条目的数量。空字典({ })始终返回 0。另见 is_empty


Array values ( ) const

返回该字典中的值列表。


操作符说明

bool operator != ( Dictionary right )

如果两个字典包含的键、值不同,则返回 true


bool operator == ( Dictionary right )

如果两个字典包含的键、值心相同,则返回 true 。条目顺序并不重要。

注意:在 C# 中,按照惯例,这个操作符进行的是按引用比较。如果你需要按值比较,请遍历这两个字典。


Variant operator [] ( Variant key )

返回该字典中与给定的键 key 对应的值。如果条目不存在或者失败,则返回 null。为了更安全的访问,请使用 gethas

Previous Next


© 版权所有 2014-present Juan Linietsky, Ariel Manzur and the Godot community (CC BY 3.0). Revision b1c660f7.

Built with Sphinx using a theme provided by Read the Docs.