Assign array name from variable when looping over another array?

Godot Version

v4.3.stable.official

Question

I realize this might be a stupid question but I have an array called ‘lists’. I want to loop over this array and use each string from the array as the key for an array in a dict called ‘list_items’. The list items are read line by line from a plain text file.

So, if the lists array was:

lists[“filename”]

And the text file I’m reading from has two lines:

item1
item2

Then I would end up with:

list_items{“filename”: [“item1”,“item2”]}

Here’s the code I’m using which doesn’t work because ‘item’ is evaluated as a string instead of as the value of the variable named ‘item’. Any ideas on how to do this correctly?

	## INDIVIDUAL LISTS
	for item in globals.lists:
		if FileAccess.file_exists("user://" + item + ".txt"):
			var file = FileAccess.open("user://" + item + ".txt", FileAccess.READ)
			globals.list_items.item = []
			while !file.eof_reached():
				var line = file.get_line()
				globals.list_items.item.append(line)
			print(globals.list_items)
		else:
			print("file not found")

Thanks in advance for any help.

So you mean the line globals.list_items.item = [], right?
To use a variable as an index in a dictionary, you can just use the [] operator, like in an array: globals.list_items[item] = []

Thanks! That worked.

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