Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

字典

A built-in data structure that holds key-value pairs.

描述

Dictionaries are associative containers that contain values referenced by unique keys. Dictionaries will preserve the insertion order when adding new entries. In other programming languages, this data structure is often referred to as a hash map or an associative array.

You can define a dictionary by placing a comma-separated list of key: value pairs inside curly braces {}.

Creating a dictionary:

var my_dict = {} # Creates an empty dictionary.

var dict_variable_key = "Another key name"
var dict_variable_value = "value2"
var another_dict = {
    "Some key name": "value1",
    dict_variable_key: dict_variable_value,
}

var points_dict = {"White": 50, "Yellow": 75, "Orange": 100}

# Alternative Lua-style syntax.
# Doesn't require quotes around keys, but only string constants can be used as key names.
# Additionally, key names must start with a letter or an underscore.
# Here, `some_key` is a string literal, not a variable!
another_dict = {
    some_key = 42,
}

You can access a dictionary's value by referencing its corresponding key. In the above example, points_dict["White"] will return 50. You can also write points_dict.White, which is equivalent. However, you'll have to use the bracket syntax if the key you're accessing the dictionary with isn't a fixed string (such as a number or variable).

@export_enum("White", "Yellow", "Orange") var my_color: String
var points_dict = {"White": 50, "Yellow": 75, "Orange": 100}
func _ready():
    # We can't use dot syntax here as `my_color` is a variable.
    var points = points_dict[my_color]

In the above code, points will be assigned the value that is paired with the appropriate color selected in my_color.

Dictionaries can contain more complex data:

var my_dict = {
    "First Array": [1, 2, 3, 4] # Assigns an Array to a String key.
}

To add a key to an existing dictionary, access it like an existing key and assign to it:

var points_dict = {"White": 50, "Yellow": 75, "Orange": 100}
points_dict["Blue"] = 150 # Add "Blue" as a key and assign 150 as its value.

Finally, dictionaries can contain different types of keys and values in the same dictionary:

# This is a valid dictionary.
# To access the string "Nested value" below, use `my_dict.sub_dict.sub_key` or `my_dict["sub_dict"]["sub_key"]`.
# Indexing styles can be mixed and matched depending on your needs.
var my_dict = {
    "String Key": 5,
    4: [1, 2, 3],
    7: "Hello",
    "sub_dict": {"sub_key": "Nested value"},
}

The keys of a dictionary can be iterated with the for keyword:

var groceries = {"Orange": 20, "Apple": 2, "Banana": 4}
for fruit in groceries:
    var amount = groceries[fruit]

Note: Dictionaries are always passed by reference. To get a copy of a dictionary which can be modified independently of the original dictionary, use duplicate.

Note: Erasing elements while iterating over dictionaries is not supported and will result in unpredictable behavior.

备注

There are notable differences when using this API with C#. See C# API 与 GDScript 的差异 for more information.

教程

构造函数

Dictionary

Dictionary ( )

Dictionary

Dictionary ( Dictionary from )

Methods

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 )


Constructor Descriptions

Dictionary Dictionary ( )

Constructs an empty Dictionary.


Dictionary Dictionary ( Dictionary from )

Returns the same dictionary as from. If you need a copy of the dictionary, use duplicate.


Method Descriptions

void clear ( )

Clears the dictionary, removing all entries from it.


Dictionary duplicate ( bool deep=false ) const

Creates and returns a new copy of the dictionary. If deep is true, inner Dictionary and Array keys and values are also copied, recursively.


bool erase ( Variant key )

Removes the dictionary entry by key, if it exists. Returns true if the given key existed in the dictionary, otherwise false.

Note: Do not erase entries while iterating over the dictionary. You can iterate over the keys array instead.


Variant find_key ( Variant value ) const

Finds and returns the first key whose associated value is equal to value, or null if it is not found.

Note: null is also a valid key. If inside the dictionary, find_key may give misleading results.


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

Returns the corresponding value for the given key in the dictionary. If the key does not exist, returns default, or null if the parameter is omitted.


bool has ( Variant key ) const

Returns true if the dictionary contains an entry with the given key.

var my_dict = {
    "Godot" : 4,
    210 : null,
}

print(my_dict.has("Godot")) # Prints true
print(my_dict.has(210))     # Prints true
print(my_dict.has(4))       # Prints false

In GDScript, this is equivalent to the in operator:

if "Godot" in {"Godot": 4}:
    print("The key is here!") # Will be printed.

Note: This method returns true as long as the key exists, even if its corresponding value is null.


bool has_all ( Array keys ) const

Returns true if the dictionary contains all keys in the given keys array.

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

int hash ( ) const

Returns a hashed 32-bit integer value representing the dictionary contents.

var dict1 = {"A": 10, "B": 2}
var dict2 = {"A": 10, "B": 2}

print(dict1.hash() == dict2.hash()) # Prints true

Note: Dictionaries with the same entries but in a different order will not have the same hash.

Note: Dictionaries with equal hash values are not guaranteed to be the same, because of hash collisions. On the contrary, dictionaries with different hash values are guaranteed to be different.


bool is_empty ( ) const

Returns true if the dictionary is empty (its size is 0). See also size.


bool is_read_only ( ) const

Returns true if the dictionary is read-only. See make_read_only. Dictionaries are automatically read-only if declared with const keyword.


Array keys ( ) const

Returns the list of keys in the dictionary.


void make_read_only ( )

Makes the dictionary read-only, i.e. disables modification of the dictionary's contents. Does not apply to nested content, e.g. content of nested dictionaries.


void merge ( Dictionary dictionary, bool overwrite=false )

Adds entries from dictionary to this dictionary. By default, duplicate keys are not copied over, unless overwrite is true.


int size ( ) const

Returns the number of entries in the dictionary. Empty dictionaries ({ }) always return 0. See also is_empty.


Array values ( ) const

Returns the list of values in this dictionary.


Operator Descriptions

bool operator != ( Dictionary right )

Returns true if the two dictionaries do not contain the same keys and values.


bool operator == ( Dictionary right )

Returns true if the two dictionaries contain the same keys and values. The order of the entries does not matter.

Note: In C#, by convention, this operator compares by reference. If you need to compare by value, iterate over both dictionaries.


Variant operator [] ( Variant key )

Returns the corresponding value for the given key in the dictionary. If the entry does not exist, fails and returns null. For safe access, use get or has.