Dictionary

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

Descripción

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, untyped 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]

To enforce a certain type for keys and values, you can create a typed dictionary. Typed dictionaries can only contain keys and values of the given types, or that inherit from the given classes:

# Creates a typed dictionary with String keys and int values.
# Attempting to use any other type for keys or values will result in an error.
var typed_dict: Dictionary[String, int] = {
    "some_key": 1,
    "some_other_key": 2,
}

# Creates a typed dictionary with String keys and values of any type.
# Attempting to use any other type for keys will result in an error.
var typed_dict_key_only: Dictionary[String, Variant] = {
    "some_key": 12.34,
    "some_other_key": "string",
}

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.

Nota

Hay diferencias notables cuando usa esta API con C#. Véase Diferencias de la API de C# con GDScript para más información.

Tutoriales

Constructores

Dictionary

Dictionary()

Dictionary

Dictionary(base: Dictionary, key_type: int, key_class_name: StringName, key_script: Variant, value_type: int, value_class_name: StringName, value_script: Variant)

Dictionary

Dictionary(from: Dictionary)

Métodos

void

assign(dictionary: Dictionary)

void

clear()

Dictionary

duplicate(deep: bool = false) const

Dictionary

duplicate_deep(deep_subresources_mode: int = 1) const

bool

erase(key: Variant)

Variant

find_key(value: Variant) const

Variant

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

Variant

get_or_add(key: Variant, default: Variant = null)

int

get_typed_key_builtin() const

StringName

get_typed_key_class_name() const

Variant

get_typed_key_script() const

int

get_typed_value_builtin() const

StringName

get_typed_value_class_name() const

Variant

get_typed_value_script() const

bool

has(key: Variant) const

bool

has_all(keys: Array) const

int

hash() const

bool

is_empty() const

bool

is_read_only() const

bool

is_same_typed(dictionary: Dictionary) const

bool

is_same_typed_key(dictionary: Dictionary) const

bool

is_same_typed_value(dictionary: Dictionary) const

bool

is_typed() const

bool

is_typed_key() const

bool

is_typed_value() const

Array

keys() const

void

make_read_only()

void

merge(dictionary: Dictionary, overwrite: bool = false)

Dictionary

merged(dictionary: Dictionary, overwrite: bool = false) const

bool

recursive_equal(dictionary: Dictionary, recursion_count: int) const

bool

set(key: Variant, value: Variant)

int

size() const

void

sort()

Array

values() const

Operadores

bool

operator !=(right: Dictionary)

bool

operator ==(right: Dictionary)

Variant

operator [](key: Variant)


Descripciones de Constructores

Dictionary Dictionary() 🔗

Construye un Dictionary vacío.


Dictionary Dictionary(base: Dictionary, key_type: int, key_class_name: StringName, key_script: Variant, value_type: int, value_class_name: StringName, value_script: Variant)

Crea un diccionario tipado desde el diccionario base. Un diccionario tipado solo puede contener claves y valores de los tipos dados, o que hereden de las clases dadas, como se describe en los parámetros de este constructor.


Dictionary Dictionary(from: Dictionary)

Devuelve el mismo diccionario que from. Si necesitas una copia del diccionario, usa duplicate().


Descripciones de Métodos

void assign(dictionary: Dictionary) 🔗

Asigna elementos de otro dictionary al diccionario. Cambia el tamaño del diccionario para que coincida con dictionary. Realiza conversiones de tipo si el diccionario está tipado.


void clear() 🔗

Limpia el diccionario, eliminando todas las entradas del mismo.


Dictionary duplicate(deep: bool = false) const 🔗

Devuelve una nueva copia del diccionario.

De forma predeterminada, se devuelve una copia superficial: todas las claves y valores anidados de Array, Dictionary y Resource se comparten con el diccionario original. Modificar cualquiera de ellos en un diccionario también los afectará en el otro.

Si deep es true, se devuelve una copia profunda: todos los arrays y diccionarios anidados también se duplican (recursivamente). Sin embargo, cualquier Resource se sigue compartiendo con el diccionario original.


Dictionary duplicate_deep(deep_subresources_mode: int = 1) const 🔗

Duplica este diccionario, profundamente, como duplicate()(true), con control adicional sobre cómo se manejan los subrecursos.

deep_subresources_mode debe ser uno de los valores de DeepDuplicateMode. De forma predeterminada, solo los recursos internos se duplicarán (recursivamente).


bool erase(key: Variant) 🔗

Elimina la entrada del diccionario por clave, si existe. Devuelve true si la key dada existía en el diccionario, de lo contrario false.

Nota: No borres entradas mientras iteras sobre el diccionario. En su lugar, puedes iterar sobre el array keys().


Variant find_key(value: Variant) const 🔗

Encuentra y devuelve la primera clave cuyo valor asociado es igual a value, o null si no se encuentra.

Nota: null también es una clave válida. Si está dentro del diccionario, find_key() puede dar resultados engañosos.


Variant get(key: Variant, default: Variant = 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.


Variant get_or_add(key: Variant, default: Variant = null) 🔗

Obtiene un valor y se asegura de que la clave está establecida. Si la key existe en el diccionario, esto se comporta como get(). De lo contrario, el valor default se inserta en el diccionario y se devuelve.


int get_typed_key_builtin() const 🔗

Devuelve el tipo Variant incorporado de las claves del diccionario tipado como una constante Variant.Type. Si las claves no están tipadas, devuelve @GlobalScope.TYPE_NIL. Véase también is_typed_key().


StringName get_typed_key_class_name() const 🔗

Devuelve el nombre de la clase incorporada de las claves del diccionario tipado, si el tipo Variant incorporado es @GlobalScope.TYPE_OBJECT. De lo contrario, devuelve un StringName vacío. Véase también is_typed_key() y Object.get_class().


Variant get_typed_key_script() const 🔗

Devuelve la instancia de Script asociada con las claves de este diccionario tipado, o null si no existe. Véase también is_typed_key().


int get_typed_value_builtin() const 🔗

Devuelve el tipo Variant incorporado de los valores del diccionario tipado como una constante Variant.Type. Si los valores no están tipados, devuelve @GlobalScope.TYPE_NIL. Véase también is_typed_value().


StringName get_typed_value_class_name() const 🔗

Devuelve el nombre de la clase incorporada de los valores del diccionario tipado, si el tipo Variant incorporado es @GlobalScope.TYPE_OBJECT. De lo contrario, devuelve un StringName vacío. Véase también is_typed_value() y Object.get_class().


Variant get_typed_value_script() const 🔗

Devuelve la instancia de Script asociada con los valores de este diccionario tipado, o null si no existe. Véase también is_typed_value().


bool has(key: Variant) 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(keys: Array) 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 🔗

Devuelve true si el diccionario está vacío (su tamaño es 0). Véase también size().


bool is_read_only() const 🔗

Devuelve true si el diccionario es de solo lectura. Véase make_read_only(). Los diccionarios son automáticamente de solo lectura si se declaran con la palabra clave const.


bool is_same_typed(dictionary: Dictionary) const 🔗

Devuelve true si el diccionario tiene el mismo tipo que dictionary.


bool is_same_typed_key(dictionary: Dictionary) const 🔗

Devuelve true si los tipos de las claves del diccionario son los mismos que los tipos de las claves de dictionary.


bool is_same_typed_value(dictionary: Dictionary) const 🔗

Devuelve true si los tipos de los valores del diccionario son los mismos que los tipos de los valores de dictionary.


bool is_typed() const 🔗

Devuelve true si el diccionario está tipado. Los diccionarios tipados solo pueden almacenar claves/valores de su tipo asociado y proporcionan seguridad de tipo para el operador []. Los métodos del diccionario tipado aún devuelven Variant.


bool is_typed_key() const 🔗

Devuelve true si las claves del diccionario están tipadas.


bool is_typed_value() const 🔗

Devuelve true si los valores del diccionario están tipados.


Array keys() const 🔗

Devuelve la lista de claves del diccionario.


void make_read_only() 🔗

Hace que el diccionario sea de solo lectura, es decir, deshabilita la modificación del contenido del diccionario. No se aplica al contenido anidado, por ejemplo, al contenido de los diccionarios anidados.


void merge(dictionary: Dictionary, overwrite: bool = false) 🔗

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

var dict = { "item": "sword", "quantity": 2 }
var other_dict = { "quantity": 15, "color": "silver" }

# Overwriting of existing keys is disabled by default.
dict.merge(other_dict)
print(dict)  # { "item": "sword", "quantity": 2, "color": "silver" }

# With overwriting of existing keys enabled.
dict.merge(other_dict, true)
print(dict)  # { "item": "sword", "quantity": 15, "color": "silver" }

Note: merge() is not recursive. Nested dictionaries are considered as keys that can be overwritten or not depending on the value of overwrite, but they will never be merged together.


Dictionary merged(dictionary: Dictionary, overwrite: bool = false) const 🔗

Returns a copy of this dictionary merged with the other dictionary. By default, duplicate keys are not copied over, unless overwrite is true. See also merge().

This method is useful for quickly making dictionaries with default values:

var base = { "fruit": "apple", "vegetable": "potato" }
var extra = { "fruit": "orange", "dressing": "vinegar" }
# Prints { "fruit": "orange", "vegetable": "potato", "dressing": "vinegar" }
print(extra.merged(base))
# Prints { "fruit": "apple", "vegetable": "potato", "dressing": "vinegar" }
print(extra.merged(base, true))

bool recursive_equal(dictionary: Dictionary, recursion_count: int) const 🔗

Returns true if the two dictionaries contain the same keys and values, inner Dictionary and Array keys and values are compared recursively.


bool set(key: Variant, value: Variant) 🔗

Establece el valor del elemento en la key dada al value dado. Esto es lo mismo que usar el operador [] (array[index] = value).


int size() const 🔗

Devuelve el número de entradas en el diccionario. Los diccionarios vacíos ({ }) siempre devuelven 0. Véase también is_empty().


void sort() 🔗

Sorts the dictionary in ascending order, by key. The final order is dependent on the "less than" (<) comparison between keys.

var numbers = { "c": 2, "a": 0, "b": 1 }
numbers.sort()
print(numbers) # Prints { "a": 0, "b": 1, "c": 2 }

This method ensures that the dictionary's entries are ordered consistently when keys() or values() are called, or when the dictionary needs to be converted to a string through @GlobalScope.str() or JSON.stringify().


Array values() const 🔗

Devuelve la lista de valores en este diccionario.


Descripciones de Operadores

bool operator !=(right: Dictionary) 🔗

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


bool operator ==(right: Dictionary) 🔗

Devuelve true si los dos diccionarios contienen las mismas claves y valores. El orden de las entradas no importa.

Nota: En C#, por convención, este operador compara por referencia. Si necesitas comparar por valor, itera sobre ambos diccionarios.


Variant operator [](key: Variant) 🔗

Devuelve el valor correspondiente para la key dada en el diccionario. Si la entrada no existe, falla y devuelve null. Para un acceso seguro, usa get() o has().