Skip to content

Add a get_or_set_default method to Dictionary #7059

Description

@aaronfranke

Describe the project you are working on

A game with a lot of dynamic code.

Describe the problem or limitation you are having in your project

I often find myself needing this pattern:

var value
if dict.has(name):
	value = dict[name]
else:
	value = default_value
	dict[name] = value

This code could also be written like this, but it involves accessing the Dictionary 3 times instead of 2:

if not dict.has(name):
	dict[name] = default_value
var value = dict[name]

Describe the feature / enhancement and how it helps to overcome the problem or limitation

I propose adding a method to handle this pattern. I'm not certain of what to call it, the best thing I can think of at the moment is get_or_set_default. I think this should be readable and convey what it does well.

Example use case:

func _ready() -> void:
	var dict: Dictionary = {}
	_add_to_array_in_dict(dict, "test1", "hi1")
	_add_to_array_in_dict(dict, "test1", "hi2")
	_add_to_array_in_dict(dict, "test2", "hi3")
	print(dict) # { "test1": ["hi1", "hi2"], "test2": ["hi3"] }


func _add_to_array_in_dict(dict: Dictionary, key: String, value: Variant) -> void:
	var array: Array = dict.get_or_set_default(key, [])
	array.append(value)

Without get_or_set_default, the _add_to_array_in_dict method would need to be 2 to 5 lines longer. The proposed get_or_set_default would also be naturally faster because it would be written in C++ instead of GDScript.

Describe how your proposal will work, with code, pseudo-code, mock-ups, and/or diagrams

godotengine/godot#78095 Add a get_or_set_default method to Dictionary and expose it.

If this enhancement will not be used often, can it be worked around with a few lines of script?

It can be worked around in a few lines of script, but it will be used often. At least, I am using it often. I have no idea how common this pattern is in other people's Godot games.

Is there a reason why this should be core and not an add-on in the asset library?

It's very tiny and heavily related to Dictionary, so it would be most optimal to put it there.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions