![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | FT_Anx |
Hi, I’m trying to add data to an empty list (or dictionary). The plan would be: A popup with EditLines would appear and would get these values: (1st) Name, (2nd) Surname, (3rd) Profession. 3 singleton variables would get the text from each. Then, I’d save in the dictionary.
names['person_name'] = name
Supposing that ‘name’ will be the singleton var that stores the name specified in the EditLine, so the plan would be to keep adding names and its keys:, and would look like something like this:
var names = [
{
'person_name': "Albert",
'surname': "Einstein",
'profession': "Physicist",
}
{ 'person_name': "Michael",
'surname': "Jordan",
'profession': "Basketball Player",
}
{
'person_name': "James",
'surname': "Bond",
'profession': "Secret Agent"
}]
(Sorry for the code mess, I tried to organize it, but failed miserably)
Then, after doing research for hours and hours… and hours and more hours, I’m not sure, but there was a post in a python forum saying it’s not possible to add keys/values to an empty list?
I don’t know, I just wanna save/add data like this in a json file and I’m happy. It’s been 10 days and nothing. Didn’t know it was that difficult. I’ll appreciate any help.
I’m trying to understand what you’re trying to do. You want a list which contains dictionaries? Building upon your example, you want elements of the list to contain dictionaries? If that’s the case, you can add elements to the list sort of like this:
var famous_person = {
'person_name' : 'George',
'surname' : 'Washington',
'profession' : 'president'
}
names.append(famous_person)
Then, when you need to do something with the information from the list, walk through the list and change or get what you want.
for person in names:
if person['person_name'] == 'George' and person['surname'] == 'Washington':
person['profession'] = 'Father of country'
Hope this puts you on the right track.
Ertain | 2019-09-13 03:52
Thanks a lot! That’s what I was looking for.
I had to do this in the singleton script, that was the only successful attempt:
func save_file_test2():
# Load
var f = File.new()
f.open(SAVE_PATH, File.READ)
var json = JSON.parse(f.get_as_text())
f.close()
var data = json.result
# Modify
var store_data ={ 'person_name': name, 'surname': surname, 'profession': profession }
# Save
f = File.new()
f.open(SAVE_PATH, File.WRITE)
if( data == null ):
f.store_string(JSON.print(store_data, " ", true))
else:
data.append(store_data)
f.store_string(JSON.print(data, " ", true))
f.close()
FT_Anx | 2019-09-13 19:29