Search code examples
pythonjupyter-notebookgoogle-colaboratorykeyerror

Solving key error of a python notebook after importation


Good day everyone. I tried importing a notebook configs.ipynb to another notebook app.ipynb. However, after importation, I got an error which is a key error. The error is below:

KeyError                                  Traceback (most recent call last)
<ipython-input-4-789a3306b22a> in <module>()
      1 import import_ipynb
----> 2 import configs

8 frames
configs.ipynb in <module>()

<decorator-gen-91> in cd(self, parameter_s)

/usr/local/lib/python3.6/dist-packages/IPython/core/magics/osm.py in cd(self, parameter_s)
    355             else:
    356                 cwd = py3compat.getcwd()
--> 357                 dhist = self.shell.user_ns['_dh']
    358                 if oldcwd != cwd:
    359                     dhist.append(cwd)

KeyError: '_dh'

This is the file in the configs.ipynb below:

from attrdict import AttrDict  # type: ignore

config = {
    "encoder_path": "/content/drive/MyDrive/decoder_model.bin",
    "decoder_path": "/content/drive/MyDrive/encoder_model.bin",
    "input_word_index": "/content/drive/MyDrive/input_word_index.pkl",
    "target_word_index": "/content/drive/MyDrive/target_word_index.pkl",
    "url": "https://api.mymemory.translated.net/get",
    "max_length_src": 47,
    "max_length_tar": 47,
}
config = AttrDict(config)

Please help me solve the error. Thank you.


Solution

  • I think you misunderstood the concept. Please correct me if I'm wrong. You're trying to import the configs function written in the configs.ipynb to another notebook right ?

    If you're doing this then you may need to copy and paste below python configs function to configs.py in the same folder where you have the another notebook app.ipynb.

    Please copy below function to configs.py file.

    from attrdict import AttrDict  # type: ignore
    
    config = {
        "encoder_path": "/content/drive/MyDrive/decoder_model.bin",
        "decoder_path": "/content/drive/MyDrive/encoder_model.bin",
        "input_word_index": "/content/drive/MyDrive/input_word_index.pkl",
        "target_word_index": "/content/drive/MyDrive/target_word_index.pkl",
        "url": "https://api.mymemory.translated.net/get",
        "max_length_src": 47,
        "max_length_tar": 47,
    }
    config = AttrDict(config)
    

    Now you file structure would be like this:

    Main Folder
    ├── configs.py # Make sure you have this.
    ├── configs.ipynb
    ├── app.ipynb
    

    then go to the app.ipynb and do the following

    import configs