Remove empty values from dictionary

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

Hi,

I’d like to remove unused values from a dictionary

Example:

CURRENT_ITEMS = {Sword:1, Shield:1,Dagger:0}

In this case, I’d like to remove Dagge from the dictionary, since it’s equal to 0
Probably by using a setget linked to the dictionary var that remove it when it detects something with value 0

The dictionary isn’t always in the same order tho, it’s randomly generated based on what the player pick up.

To give some context, I’m looking to create an interface displaying the CURRENT_ITEMS dictionary. It can not be edited tho, just displayed, and updated whenever a player pickup an item; For this, I use a Inventory Grid with TextureButton, and I’m hopping to be able to somehow link the TextureButton to the dictionary

:bust_in_silhouette: Reply From: Zylann

If you are given a dictionary with any number of potential 0 values, you could do that:

# using `.keys()` because we are removing pairs from the dictionary
# while iterating it, could cause issues otherwise
for key in dictionary.keys():
	if dictionary[key] == 0:
		dictionary.erase(key)

But you can also simply erase the value while setting it, instead of setting to zero:

var count = dictionary[key]
count -= amount_to_remove
if count == 0:
	dictionary.erase(key)
else
	dictionary[key] = count

As for binding data to your UI, this is a very different question, more involved, which could be answered by entire tutorials (but here is not the right place for that).
One thing I’d try is have a function to “update the GUI from the data”, and that function would remove widgets that target a key that no longer exists, and add widgets for keys that have no widget yet.
You could also consider just rebuilding the GUI entirely with code if it’s small enough.