Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to update this dictionary

tickets is an empty dictionary in a file called Cities. I want to update the dictionary with new values after every time I run this program, but it ends up erasing the dictionary and adding only 1 key-value pair.

from Cities import tickets

a = {random.randint(1,999): random.randint(1,89898)}
tickets.update(a)
print(tickets)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you want to keep the state between different executions of your script, you need to write to disk. Hence I suggest you use the built-in module shelve, as follows:

# cities.py
import shelve
tickets = shelve.open("data")

then use it from your script:

import random
from cities import tickets

with tickets:
    print(list(tickets.items()))
    a = {f"{random.randint(1, 999)}": random.randint(1, 89898)}
    tickets.update(a)

Output (first run)

[]

Output (second run)

[('900', 67984)]

The only caveat though is that the keys need to be strings.

Note: (from the docs) Do not rely on the shelf being closed automatically; always call close() explicitly when you don’t need it any more, or use shelve.open() as a context manager.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading