Adding to a key in a dictionary using a variable

Godot Version

4.4

Question

I am making a music player in Godot, and I’m trying to add a song into a playlist.

Here’s the function:

func add_song_to_playlist(playlist_name: String):
	 for playlist in playlist_list:
		if playlist == playlist_name:
			playlist_list[playlist].get_or_add(song_to_add_to_playlist)

In theory, it should work. The playlist_list is a dictionary with at least a “Favorites” key (which when asked to get keys returns it) that is an empty (null) dictionary. And the playlist var in the for loop is getting each key in the list. However, no matter how I try to check if the playlist_name is a key in the list, it doesn’t work.

The playlist var should be the key, so all I’d need to do is make sure that the key matches the string of the playlist_name (which in testing it does) and then add the song_to_add_to_playlist (which is set earlier when a button is pressed) to the key of the dictionary.

But whenever I run it, I get the error “Invalid call. Nonexistent function ‘get_or_add’ in base ‘Nil’.”

I don’t know what’s going on, and it’s probably something simple, but I’d love some thoughts on why this is/how I can fix it. Thanks.

I miss read the problem

1 Like

This will get the existing value if the key exists or add a null value, as the default, if the key doesnt exist. You probably need to add the value here too maybe?

You probably need to make sure when you add a playlist you create the dictionary first

1 Like

I found out the issue. The playlist_list was set to {Favorites:null}, which is just a null key, not a dictionary. I changed it to {"Favorites":{}} (making it a dictionary) and it worked.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.