Home > Net >  save a dictionary to a .db file
save a dictionary to a .db file

Time:08-17

for the past couple of hours, I've been trying to find a solution to this issue. Any knowledge share is very helpful. The objective is to save the dictionary created from the program. I am getting an error in line 3.

 def save_dict(dictionary_to_be_saved): 
    with shelve.open('OperationNamesDictionary.db', 'c') as s: #create OperationNamesDictionary.db
        s = dictionary_to_be_saved    

What am I planning to achieve? : I have to pass the dictionary name to this function and it should create a (****.db) file, which I can use later.

Thanks in advance

Code used to save a dictionary:

def save_dict(dictionary_to_be_saved): 
    with shelve.open('OperationNamesDictionary.db', 'c') as s:  #  "c" flag used to create dictionary
        s = dictionary_to_be_saved  

Code used to retrieve a dictionary from created file:

def load_dict():
    try:
        with shelve.open('TOperationNamesDictionary.db', 'r') as s: 
         operation_names =  s
         return(operation_names)
    except dbm.error:
        print("Could not find a saved dictionary, using a pre-coded one.")


operation_names = load_dict()
print(operation_names)

output:<shelve.DbfilenameShelf object at 0x0000021970AD89A0> Expected output: data inside the operation_names (A dictionary)

CodePudding user response:

I think this is what you are after, more or less. This is untested code so I hope it works! What I have added to your attempts in the question is to provide a key value for the items you are shelving (I used the uninteresting identifier "mydictionary" as my key). So we put items in by that name, and take them out again by that same name.

def save_dict(dictionary_to_be_saved): 
    with shelve.open('OperationNamesDictionary.db', 'c') as s:
        s['mydictionary'] = dictionary_to_be_saved  

def load_dict():
    try:
        with shelve.open('TOperationNamesDictionary.db', 'r') as s: 
            return s['mydictionary']
    except KeyError:
        print("Could not find a saved dictionary")

CodePudding user response:

For my specific case, creating a (.npy) file worked for me. Again, the objective of my code is to use a dictionary that is available (the type of file that stores this dictionary doesn't matter) and at the end of the program save the updated dictionary to the same file.

import numpy as np

try: 
 operation_names = np.load("Operation_Dictionary.npy", allow_pickle = 'TRUE').item()
 print("Using the Dictionary which is found in Path")

except FileNotFoundError:
 print("Using Pre-coded Dictionary from the code")
 operation_names = {"Asd-013we":"No Influence", "rdfhyZ1":"TRM"}# default dictionary
.....
.....
# the program will update the dictionary

np.save("Operation_Dictionary.npy",operation_names) #the updated dictionary is saved to same file. 
  • Related