how to get name in my dict?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By potatobanana

if i do like this

var dict = {
  "stats": {
	"strength": 0,
	"constitution": 0,
	"intelligence": 5,
	"wisdom": 1,
	"dexterity": 0,
	"agility": 0

func _ready() → void:
i get this
{agility:0, constitution:0, dexterity:0, intelligence:5, strength:0, wisdom:1}

if i do like this
i get this

but i want this
{intelligence:5, strength:0, wisdom:1}

Can you more clearly explain what you’re trying to do?
You’re asking how to “get name in my dict” but then you say that you want {intelligence:5, strength:0, wisdom:1}, which is a subset of the key-value pairs in dict["stats"]. Please clarify what you mean.
Do you just want to be able to print the dict key along with the value?
If so, you can easily create a function like this:

extends Node

const STAT_NAME := {
	strength = "strength",
	constitution = "constitution",
	intelligence = "intelligence",
	wisdom = "wisdom",
	dexterity = "dexterity",
	agility = "agility"

var dict := {
  "stats": {
	STAT_NAME.strength: 0,
	STAT_NAME.constitution: 0,
	STAT_NAME.intelligence: 5,
	STAT_NAME.wisdom: 1,
	STAT_NAME.dexterity: 0,
	STAT_NAME.agility: 0

func print_stat(stat_name: String) -> void:
	var stat_dict: Dictionary = dict["stats"]
	assert(stat_dict.keys().hash() == STAT_NAME.keys().hash(), "Keys don't match")
	assert(stat_dict.has(stat_name), str("Not in dict: ", stat_name))
	print(stat_name, ": ", stat_dict[stat_name])

func print_all_stats() -> void:
	for stat_name in STAT_NAME.values():

func _ready():
	print("--- Printing single stat value ---")
	print("--- Printing all stat values ---")


--- Printing single stat value ---
intelligence: 5

--- Printing all stat values ---
strength: 0
constitution: 0
intelligence: 5
wisdom: 1
dexterity: 0
agility: 0

Error7Studios | 2021-02-21 05:59

thanks, what i want is sub key name(not value), then take few key to print ,
i can do single stat value like you show up there . :slight_smile: and i try to find easy way to do, like get_node().get_name. seems like my_dictionnary.keys() work too

potatobanana | 2021-02-23 11:17

:bust_in_silhouette: Reply From: Lopy

To get all of the keys in your Dictionnary, simply call my_dictionnary.keys().
If you want to print the key-value pairs for instance, you could do:

for key in my_dictionnary.keys():
    prints("Key", key, "has a value of", my_dictionnary[key])

If you want to work only on a subset of key-value pairs, without altering the original Dictionnary, you can create a copy of it with my_dictionnary.duplicate(). This will return an independent Dictionnary, meaning you can call erase on it to remove unwanted pairs.

thanks ,this what i need

potatobanana | 2021-02-23 11:06