0

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)

Nayasaal
  • 1
  • 4
  • What error are you getting? Can you edit your question and put there the whole error stack trace? – Andrej Kesely Aug 15 '22 at 23:34
  • It looks like you are creating a shelf but not putting anything in it or taking anything out of it. In particular this line does not save anything in a db file: `s = dictionary_to_be_saved` - all it does is create a variable names `s`, which is a reference to the dictionary. Likewise, this does not read anything: `operation_names = s` - all it does is create a variable named operation_names, which is a reference to the shelf. There are examples to follow in the [docs](https://docs.python.org/3/library/shelve.html) - you should read through this carefully for understanding. – topsail Aug 16 '22 at 00:30
  • @topsail Can you explain a bit more about how to save the dictionary? I have understood the part about creating a shelf. But how do i save my dictionary to that shelf? I have read the Python doc, but not able to digest the technical jargon. (please bear with me, as I just started learning Python) – Nayasaal Aug 16 '22 at 00:50
  • Generally you want to start by just looking at the examples (when you can't understand the technical jargon) - usually in python docs the examples are very straightforward. The reason they call shelfs "dictionary-like" is because you put items in them with a key, and you take items out of them with a key - using the same syntax as dictionary i.e., `myshelf[key]` – topsail Aug 16 '22 at 01:23

2 Answers2

0

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")
topsail
  • 2,186
  • 3
  • 17
  • 17
  • The objective of my code is to first look for a dictionary (saved as a .db or any other format; security is not a concern) if it's available in the directory. If its not available, the code will start the program by using an explicitly mentioned dictionary in the code. ` #The code uses the dictionary to find keys, and if its not found, it will ask the user to enter #the value so that it updates the dictionary with this new key: value. #At the end of the program, the dictionary will be saved to be used later. (should be updatable again) ` – Nayasaal Aug 16 '22 at 16:17
  • a shelf requires a key so you can't just "look for a dictionary". You could possibly look for a db file, check its keys, see if any of its keys have dictionaries in them. I didn't see anything specific in the documents about getting a list of keys from a shelf - it may or may not be possible. I guess in general I would prefer just serializing a dictionary directly (with pickle or something like that) rather than using a shelf though. But maybe its only because I've never used shelfs and I don't know this object well. Using a shelf will be easier if you know the key you save your dicts with. – topsail Aug 16 '22 at 21:04
0

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. 
Nayasaal
  • 1
  • 4