[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Help on dictionaries...

On 2020-01-30 06:44, Souvik Dutta wrote:
> Hey I was thinking how I can save a dictionary in python(obviously)
> so that the script is rerun it automatically loads the dictionary.

This is almost exactly what the "dbm" (nee "anydbm") module does, but
persisting the dictionary out to the disk:

  import dbm
  from sys import argv
  with"my_cache", "c") as db:
    if len(argv) > 1:
      key = argv[1]
      if key in db:
        print("Found it:", db[key])
        print("Not found. Adding")
        if len(argv) > 2:
          value = argv[2]
          value = key
        db[key] = value
      print("There are %i items in the cache" % len(db))

The resulting "db" acts like a dictionary, but persists.

If you really must have the results as a "real" dict, you can do the

  real_dict = dict(db)