0

Python - I have an empty dictionary in my program that will later be filled. Is there a way I can stop it from being emptied when I run the program again?

Beginning of program dictionary - DATABASE = {}

END of program dictionary - DATABASE = {"Hello":1, "BYE":2} (I want it to stay like this when I run the program again)

RUNNING NEW PROGRAM - DATABASE = {} (I don't want it to get reset)

Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22
  • 1
    You can probably save it to a json file. – Mike67 Sep 05 '20 at 22:16
  • The general problem is called *persistence* (for the act of storing the information) or *serialization* (for the act of converting the information into something that can be stored). That will hopefully help you do a web search (tool recommendations are off-topic for Stack Overflow). You cannot "stop" the dictionary from "being emptied" at the start of the program, because it is not the same dictionary you filled - it's in a completely separate runtime, and was never full to begin with. You need to use the persistent data to re-fill it. – Karl Knechtel Sep 05 '20 at 23:22

1 Answers1

1

Once you run a program you compiler reserves some RAM memory (volatile) and allocate your dictionary there, so you can have access to it while your code is running (the instance of your code which is a process). So, the reason you cannot keep a variable (dictionary in this case) is because it's not been saved in a NON-VOLATILE storage and then, as soon as the execution of the process stops, all the RAM space reserved for your variables is released.

If you want to keep the dictionary information, I recommend you to use an actual database, or you can just save the content of your dictionary into a file and read it at the begining of your code. Here you have some examples:

BBDD: I really recommend you to start using databases as you will find it very useful in the future.

Read/Write file: simple read/write operations.

Dump file: save information to a binary file, is better than the simple read/write.

emichester
  • 189
  • 9
  • *"I really recommend you to start using databases as you will find it very useful in the future."* Although it's always good to learn the bigger things, it may be overkill to recommend going that way for this specific question. – 89f3a1c Sep 05 '20 at 22:47
  • I want to start by saying that this is my first response in stack-overflow. I understand that using databases can be a big challenge when you start programming. But honestly, if my teachers had taught me from the beginning how to use them or at least encouraged me to do some research on them, I would have learned many useful things that I know today. It is always good to encourage people to learn :) Anyway, thanks for the remark, I'll have it in mind. – emichester Sep 05 '20 at 23:17