Home > Back-end >  I want to update this dictionary
I want to update this dictionary

Time:08-06

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)

CodePudding user response:

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.

  • Related