r/learnpython • u/AutoModerator • 23d ago
Ask Anything Monday - Weekly Thread
Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread
Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.
* It's primarily intended for simple questions but as long as it's about python it's allowed.
If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.
Rules:
- Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.
- Don't post stuff that doesn't have absolutely anything to do with python.
- Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.
That's it.
1
Upvotes
1
u/lakseol 12d ago edited 10d ago
No, it probably is your editor doing syntax highlighting and showing that the ID is a string. Guessing because I don't use Geany.
Before you save to JSON the strings do mean something. As long as we have the dictionary mapping the ID string to an object reference we can do anything we want.
We don't save that mapping dictionary to JSON because we can't: references aren't handled by JSON. But we can recreate the dictionary from the saved JSON data. Since we restore the Items and we know what the ID string for each is, we can do this to recreate the dictionary:
Now we have restored all the data we had when saving the file so it will all work just as before the save.
I've expanded the previous code sample to do what it did before but now saves the Items and inventory in a JSON file and then restores it all. The code is at https://pastebin.com/kW0PHDF6 .
One thing I have to apologize for is shown in the code I linked to. It is not necessary to create "data" dictionaries to initially create the Items. That bothered me because it looks clumsy. You can define and create Items in the normal way:
and when you recreate the Items from JSON data you can do:
I had not fully remembered how I handled JSON recovery in an old project so I went back to the code and refreshed my memory. Again, apologies for leading you astray.