0 votes

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

Godot version 3.4
in Engine by (21 points)

1 Answer

+2 votes

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.

by (29,036 points)
edited by
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 Frequently asked questions and 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 [email protected] with your username.