How to get the value of dictionary that could be nested?

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

var whole_dictionary = {"dictionary1":{"dictionary1.1":{"dictionary1.1.1":{"key1":"value1","key2":"value2"}}},"dictionary2":{"dictionary2.1":{"key1":"value1"}},"dictionary3":{"key1":"value1"},"key1":value1}

How can I get every value no matter how deep it goes?
I want to change the value of key2 (here value2) doing something like: search for key2. If key2 exists more than one time, do nothing, else change its value.

:bust_in_silhouette: Reply From: njamster

You have to code that yourself. Here’s a rather inefficient, but working version I’ve quickly hacked together:

var whole_dictionary = # ...

# you cannot use this symbol in your dictionary keys any longer!
const SPLIT_SYMBOL = "/" 

func _ready():
	print("Before:", whole_dictionary)
	replace_value(whole_dictionary, "key2", "new_value")
	print("After:", whole_dictionary)

func replace_value(dict, key, new_value):
	var hits = search_for(whole_dictionary, key)

	if hits.size() == 1:
		var path = hits[0].split(SPLIT_SYMBOL)
		var temp = dict
		for key in path:
			if temp[key] is Dictionary:
				temp = temp[key]
				temp[key] = new_value

func search_for(dict, query):
	var hits = []
	for key in dict.keys():
		if dict[key] is Dictionary:
			var ret = search_for(dict[key], query)
			for subkey in ret:
				hits.append(key + SPLIT_SYMBOL + subkey)
		elif key == query:
	return hits

Though the real question here is: What are you trying to do that requires replacing a certain value in a (apparently very deeply) nested dictionary if and only if the key this value is stored under is completely unique for that mega-dictionary?

I’m having a hard time picturing a situation where one would need this.

Wow, thank you so much. I have a save system → see here and in the files where I saved something, there can be such dicts. I don’t want to write such a long line just for saving a variable and its value in the file as it’s “saved” in the variable, I just want to have this way, so I can be much lazier. It would be better if there was a way no symbol is blocked but this is a luxury problem ;D

MaaaxiKing | 2020-06-12 17:31