0 votes
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.

in Engine by (380 points)
retagged by

1 Answer

+1 vote
Best answer

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.

by (10,469 points)
selected by

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.