Dictionary
Una struttura dati incorporata che contiene coppie chiave-valore.
Descrizione
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,
}
var myDict = new Godot.Collections.Dictionary(); // Creates an empty dictionary.
var pointsDict = new Godot.Collections.Dictionary
{
{ "White", 50 },
{ "Yellow", 75 },
{ "Orange", 100 },
};
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]
[Export(PropertyHint.Enum, "White,Yellow,Orange")]
public string MyColor { get; set; }
private Godot.Collections.Dictionary _pointsDict = new Godot.Collections.Dictionary
{
{ "White", 50 },
{ "Yellow", 75 },
{ "Orange", 100 },
};
public override void _Ready()
{
int points = (int)_pointsDict[MyColor];
}
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.
}
var myDict = new Godot.Collections.Dictionary
{
{ "First Array", new Godot.Collections.Array { 1, 2, 3, 4 } }
};
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.
var pointsDict = new Godot.Collections.Dictionary
{
{ "White", 50 },
{ "Yellow", 75 },
{ "Orange", 100 },
};
pointsDict["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" },
}
// This is a valid dictionary.
// To access the string "Nested value" below, use `((Godot.Collections.Dictionary)myDict["sub_dict"])["sub_key"]`.
var myDict = new Godot.Collections.Dictionary {
{ "String Key", 5 },
{ 4, new Godot.Collections.Array { 1, 2, 3 } },
{ 7, "Hello" },
{ "sub_dict", new Godot.Collections.Dictionary { { "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]
var groceries = new Godot.Collections.Dictionary { { "Orange", 20 }, { "Apple", 2 }, { "Banana", 4 } };
foreach (var (fruit, amount) in groceries)
{
// `fruit` is the key, `amount` is the value.
}
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",
}
// 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 typedDict = new Godot.Collections.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 typedDictKeyOnly = new Godot.Collections.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
Ci sono differenze sostanziali quando si usa questa API con C#. Vedi Differenze dell'API C# rispetto a GDScript per maggiori informazioni.
Tutorial
Costruttori
Dictionary(base: Dictionary, key_type: int, key_class_name: StringName, key_script: Variant, value_type: int, value_class_name: StringName, value_script: Variant) |
|
Dictionary(from: Dictionary) |
Metodi
void |
assign(dictionary: Dictionary) |
void |
clear() |
duplicate_deep(deep_subresources_mode: int = 1) const |
|
get_or_add(key: Variant, default: Variant = null) |
|
get_typed_key_builtin() const |
|
get_typed_key_class_name() const |
|
get_typed_key_script() const |
|
get_typed_value_builtin() const |
|
get_typed_value_class_name() const |
|
get_typed_value_script() const |
|
hash() const |
|
is_empty() const |
|
is_read_only() const |
|
is_same_typed(dictionary: Dictionary) const |
|
is_same_typed_key(dictionary: Dictionary) const |
|
is_same_typed_value(dictionary: Dictionary) const |
|
is_typed() const |
|
is_typed_key() const |
|
is_typed_value() const |
|
keys() const |
|
void |
|
void |
merge(dictionary: Dictionary, overwrite: bool = false) |
merged(dictionary: Dictionary, overwrite: bool = false) const |
|
recursive_equal(dictionary: Dictionary, recursion_count: int) const |
|
size() const |
|
void |
sort() |
values() const |
Operatori
operator !=(right: Dictionary) |
|
operator ==(right: Dictionary) |
|
operator [](key: Variant) |
Descrizioni dei costruttori
Dictionary Dictionary() 🔗
Costruisce un Dictionary vuoto.
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 dizionario tipizzato dal dizionario base. Un dizionario tipizzato può contenere solo chiavi e valori dei tipi specificati, o che ereditano dalle classi specificate, come descritto dai parametri di questo costruttore.
Dictionary Dictionary(from: Dictionary)
Restituisce lo stesso dizionario di from. Se hai bisogno di una copia del dizionario, usa duplicate().
Descrizioni dei metodi
void assign(dictionary: Dictionary) 🔗
Assegna elementi di un altro dictionary in questo dizionario. Ridimensiona il dizionario per corrispondere a dictionary. Esegue le conversioni di tipo se il dizionario è tipizzato.
void clear() 🔗
Pulisce il dizionario, rimuovendo tutte le voci da esso.
Dictionary duplicate(deep: bool = false) const 🔗
Restituisce una nuova copia del dizionario.
Normalmente, viene restituita una copia superficiale: tutti gli elementi annidati di tipo Array, Dictionary e Resource sono condivisi con il dizionario originale. Modificarli in un dizionario li influenzerà anche nell'altro.
Se deep è true, viene restituita una copia profonda: anche tutti gli array e i dizionari annidati sono duplicati (ricorsivamente). Tuttavia, qualsiasi oggetto Resource rimane condiviso con il dizionario originale.
Dictionary duplicate_deep(deep_subresources_mode: int = 1) const 🔗
Duplica questo dizionario profondamente, come duplicate()(true), con ulteriore controllo su come le sottorisorse sono gestite.
deep_subresources_mode deve essere uno dei valori di DeepDuplicateMode. Come predefinito, solo le risorse interne saranno duplicate (ricorsivamente).
Rimuove la voce del dizionario per chiave, se esiste. Restituisce true se la key specificata esisteva nel dizionario, altrimenti false.
Nota: Non rimuovere le voci durante l'iterazione sul dizionario. Puoi iterare sull'array di keys() invece.
Variant find_key(value: Variant) const 🔗
Trova e restituisce la prima chiave il cui valore associato è uguale a value, o null se non viene trovato.
Nota: Anche null è una chiave valida. Se è all'interno del dizionario, find_key() potrebbe dare risultati ingannevoli.
Variant get(key: Variant, default: Variant = null) const 🔗
Restituisce il valore corrispondente per la chiave key nel dizionario. Se la chiave key non esiste, restituisce default, o null se il parametro è omesso.
Variant get_or_add(key: Variant, default: Variant = null) 🔗
Ottiene un valore e assicura che la chiave sia impostata. Se la chiave key esiste nel dizionario, si comporta come get(). Altrimenti, il valore default viene inserito nel dizionario e restituito.
int get_typed_key_builtin() const 🔗
Restituisce il tipo di Variant integrato delle chiavi del dizionario tipizzato come constante di Variant.Type. Se le chiavi non sono tipizzate, restituisce @GlobalScope.TYPE_NIL. Vedi anche is_typed_key().
StringName get_typed_key_class_name() const 🔗
Restituisce il nome della classe integrata delle chiavi del dizionario tipizzato, se il tipo di Variant incorporato è @GlobalScope.TYPE_OBJECT. Altrimenti, restituisce un StringName vuoto. Vedi anche is_typed_key() e Object.get_class().
Variant get_typed_key_script() const 🔗
Restituisce l'istanza di Script associata alle chiavi di questo dizionario tipizzato, o null se non esiste. Vedi anche is_typed().
int get_typed_value_builtin() const 🔗
Restituisce il tipo di Variant integrato dei valori del dizionario tipizzato come constante di Variant.Type. Se i valori non sono tipizzati, restituisce @GlobalScope.TYPE_NIL. Vedi anche is_typed_value().
StringName get_typed_value_class_name() const 🔗
Restituisce il nome della classe integrata dei valori del dizionario tipizzato, se il tipo di Variant integrato è @GlobalScope.TYPE_OBJECT. Altrimenti, restituisce un StringName vuoto. Vedi anche is_typed_value() e Object.get_class().
Variant get_typed_value_script() const 🔗
Restituisce l'istanza di Script associata ai valori di questo dizionario tipizzato, o null se non esiste. Vedi anche is_typed_value().
bool has(key: Variant) const 🔗
Restituisce true se il dizionario contiene una voce con la key specificata.
var my_dict = {
"Godot" : 4,
210 : null,
}
print(my_dict.has("Godot")) # Stampa true
print(my_dict.has(210)) # Stampa true
print(my_dict.has(4)) # Stampa false
var myDict = new Godot.Collections.Dictionary
{
{ "Godot", 4 },
{ 210, default },
};
GD.Print(myDict.ContainsKey("Godot")); // Stampa True
GD.Print(myDict.ContainsKey(210)); // Stampa True
GD.Print(myDict.ContainsKey(4)); // Stampa False
In GDScript, questo è equivalente all'operatore in:
if "Godot" in { "Godot": 4 }:
print("La chiave è qui!") # Verrà stampato.
Nota: Questo metodo restituisce true finché esiste la chiave key, anche se il suo valore corrispondente è null.
bool has_all(keys: Array) const 🔗
Restituisce true se il dizionario contiene tutte le chiavi nell'array keys specificato.
var data = { "larghezza" : 10, "altezza" : 20 }
data.has_all(["altezza", "larghezza"]) # Restituisce true
Restituisce un valore intero di hash a 32 bit che rappresenta il contenuto del dizionario.
var dict1 = { "A": 10, "B": 2 }
var dict2 = { "A": 10, "B": 2 }
print(dict1.hash() == dict2.hash()) # Stampa true
var dict1 = new Godot.Collections.Dictionary{ {"A", 10 }, { "B", 2 } };
var dict2 = new Godot.Collections.Dictionary{ {"A", 10 }, { "B", 2 } };
// Godot.Collections.Dictionary non ha un metodo Hash(). Usa invece GD.Hash().
GD.Print(GD.Hash(dict1) == GD.Hash(dict2)); // Stampa true
Nota: I dizionari con le stesse voci ma in un ordine diverso non avranno lo stesso hash.
Nota: I dizionari con valori uguali di hash non sono garantiti di essere uguali, a causa delle collisioni di hash. Al contrario, i dizionari con valori diversi di hash sono sicuramente diversi.
Restituisce true se il dizionario è vuoto (la sua dimensione è 0). Vedi anche size().
Restituisce true se il dizionario è di sola lettura. Vedi make_read_only(). I dizionari sono automaticamente di sola lettura se dichiarati con la parola chiave const.
bool is_same_typed(dictionary: Dictionary) const 🔗
Restituisce true se il dizionario è tipizzato nello stesso modo di dictionary.
bool is_same_typed_key(dictionary: Dictionary) const 🔗
Restituisce true se le chiavi del dizionario sono tipizzate nello stesso modo delle chiavi di dictionary.
bool is_same_typed_value(dictionary: Dictionary) const 🔗
Restituisce true se i valori del dizionario sono tipizzati nello stesso modo dei valori di dictionary.
Restituisce true se il dizionario è tipizzato. I dizionari tipizzati possono memorizzare solo chiavi/valori del tipo associato e fornire sicurezza di tipo per l'operatore []. I metodi del dizionario tipizzato restituiscono comunque Variant.
Restituisce true se le chiavi del dizionario sono tipizzate.
Restituisce true se i valori del dizionario sono tipizzati.
Restituisce la lista delle chiavi nel dizionario.
void make_read_only() 🔗
Rende il dizionario di sola lettura, ovvero disabilita la modifica del contenuto del dizionario. Non si applica al contenuto innestato, ad esempio il contenuto dei dizionari innestati.
void merge(dictionary: Dictionary, overwrite: bool = false) 🔗
Aggiunge voci da dictionary a questo dizionario. Per impostazione predefinita, le chiavi duplicate non vengono copiate, a meno che overwrite non sia true.
var dict = { "item": "sword", "quantity": 2 }
var other_dict = { "quantity": 15, "color": "silver" }
# La sovrascrittura delle chiavi esistenti è disabilitata per impostazione predefinita.
dict.merge(other_dict)
print(dict) # { "item": "sword", "quantity": 2, "color": "silver" }
# Con la sovrascrittura delle chiavi esistenti abilitata.
dict.merge(other_dict, true)
print(dict) # { "item": "sword", "quantity": 15, "color": "silver" }
var dict = new Godot.Collections.Dictionary
{
["item"] = "sword",
["quantity"] = 2,
};
var otherDict = new Godot.Collections.Dictionary
{
["quantity"] = 15,
["color"] = "silver",
};
// La sovrascrittura delle chiavi esistenti è disabilitata per impostazione predefinita.
dict.Merge(otherDict);
GD.Print(dict); // { "item": "sword", "quantity": 2, "color": "silver" }
// Con la sovrascrittura delle chiavi esistenti abilitata.
dict.Merge(otherDict, true);
GD.Print(dict); // { "item": "sword", "quantity": 15, "color": "silver" }
Nota: merge() non è ricorsivo. I dizionari annidati sono considerati chiavi che possono essere sovrascritte o meno a seconda del valore di overwrite, ma non verranno mai uniti insieme.
Dictionary merged(dictionary: Dictionary, overwrite: bool = false) const 🔗
Restituisce una copia di questo dizionario unita all'altro dictionary. Per impostazione predefinita, le chiavi duplicate non vengono copiate, a meno che overwrite non sia true. Vedi anche merge().
Questo metodo è utile per creare rapidamente dizionari con valori predefiniti:
var base = { "fruit": "apple", "vegetable": "potato" }
var extra = { "fruit": "orange", "dressing": "vinegar" }
# Stampa { "fruit": "orange", "vegetable": "potato", "dressing": "vinegar" }
print(extra.merged(base))
# Stampa { "fruit": "apple", "vegetable": "potato", "dressing": "vinegar" }
print(extra.merged(base, true))
bool recursive_equal(dictionary: Dictionary, recursion_count: int) const 🔗
Restituisce true se i due dizionari contengono le stesse chiavi e valori, le chiavi e i valori interni di tipo Dictionary e Array sono confrontati ricorsivamente.
bool set(key: Variant, value: Variant) 🔗
Imposta il valore dell'elemento nella chiave key sul valore value. È lo stesso che usare l'operatore [] (array[index] = value).
Restituisce il numero di voci nel dizionario. I dizionari vuoti ({ }) restituiscono sempre 0. Vedi anche is_empty().
void sort() 🔗
Ordina il dizionario in ordine crescente, per chiave. L'ordine finale dipende dal confronto "minore di" (<) tra le chiavi.
var numbers = { "c": 2, "a": 0, "b": 1 }
numbers.sort()
print(numbers) # Stampa { "a": 0, "b": 1, "c": 2 }
Questo metodo garantisce che le voci del dizionario siano ordinate consistentemente quando vengono chiamati keys() o values(), oppure quando c'è bisogno di convertire il dizionario in una stringa attraverso @GlobalScope.str() o JSON.stringify().
Restituisce la lista dei valori in questo dizionario.
Descrizioni degli operatori
bool operator !=(right: Dictionary) 🔗
Restituisce true se i due dizionari non contengono le stesse chiavi e valori.
bool operator ==(right: Dictionary) 🔗
Restituisce true se i due dizionari contengono le stesse chiavi e valori. L'ordine delle voci non ha importanza.
Nota: In C#, per convenzione, questo operatore confronta per riferimento. Se devi confrontare per valore, itera su entrambi i dizionari.
Variant operator [](key: Variant) 🔗
Restituisce il valore corrispondente per la chiave key nel dizionario. Se la voce non esiste, fallisce e restituisce null. Per un accesso sicuro, usa get() o has().