Changing variables of imported module doesnt seem to work. [Python]
Question: I am trying to make a separate dictionary in a python file, so I could import
it and do stuff such as search key, add word, remove word. The file is
dictionary.py . It contains:

    
    
    #-*-coding:utf8-*-
    dict={}
    

So when I import it in my main python file, add a word and print it, it works
fine, but the dictionary.py file doesn't gets affected. I want the "dict"
variable in dictionary.py file to change too. Here's my code for the main
file:

    
    
    import os
    import sys
    import dictionary as tdict
    print ":::::::::::::::::::"
    print "Add word"
    print ":::::::::::::::::::"
    name=raw_input("Word: ")
    print
    mean=raw_input ("Meaning: ")
    tdict.dict[name]=mean
    print "::::Word added::::"
    print
    print "::::::::::::::::::::::"
    print "Dictionary:"
    print
    for x in tdict.dict:
        print "",x,":",tdict.dict[x]`
    

Any help? thx


Answer: You are not writing to the file at any point. The correct way to store a
python object such as a dictionary is to use `pickle`:

    
    
    import pickle
    
    
    myDictionary = {}
    dictionaryFile = open('dictionary', 'wb')
    pickle.dump(mydictionary, dictionaryFile)
    dictionaryFile.close()
    

This will create a pickle file called `dictionary` that contains
`myDictionary`

To read the dictionary:

    
    
    import pickle
    
    
    dictionaryFile = open('dictionary', 'rb')
    myDictionary = pickle.load(dictionaryFile)
    dictionaryFile.close()
    

Then you can make whatever changes you want to the dictionary then save it to
the file again:

    
    
    import pickle
    
    
    dictionaryFile = open('dictionary', 'rb')
    myDictionary = pickle.load(dictionaryFile)
    dictionaryFile.close()
    
    myDictionary['key1'] = 'value1'
    
    dictionaryFile = open('dictionary', 'wb')
    pickle.dump(mydictionary, dictionaryFile)
    dictionaryFile.close()
    

