use pickle to save dictionary in python
Question: I have a file `hash_db.pickle` that when I created it I saved a dictionary on
it:

    
    
    v = {hash_value:{"file name":file_name,"file size":file_size,"last scanned time":scanned_time}}
    
    {123dfre345:{"file name":calc.pdf,"file size":234,"last scanned time":12:23 24/12/2013}}
    {3gcdshj754:{"file name":star.pdf,"file size":10,"last scanned time":10:30 10/10/2013}}
    

so if I want to change from the file only `last scanned time` for `3gcdshj754`

how could I do that?


Answer: You can use `pickle`.

    
    
    import pickle
    d = pickle.load(open('hash_db.pickle', 'rb'))
    d['3gcdshj754']['last scanned time'] = '11:30 11/10/2015'
    pickle.dump(d, open('hash_db.pickle', 'wb'))
    

But you might find the
[`shelve`](https://docs.python.org/2/library/shelve.html) module a little more
convenient than direct use of pickle. It provides a persistent dictionary
which seems to be exactly what you want. Sample usage:

    
    
    import shelve
    from datetime import datetime, timedelta
    
    # create a "shelf"
    shelf = shelve.open('hash_db.shelve')
    shelf['123dfre345'] = {"file name": 'calc.pdf', "file size": 234, "last scanned time": datetime(2013, 12, 24, 12, 23)}
    shelf['3gcdshj754'] = {"file name": 'star.pdf', "file size": 10, "last scanned time": datetime(2013, 10, 10, 10, 30)}
    shelf.close()
    
    # open, update and close
    shelf = shelve.open('hash_db.shelve')
    file_info = shelf['3gcdshj754']
    file_info['last scanned time'] += timedelta(hours=+1, minutes=12)
    shelf['3gcdshj754'] = file_info
    shelf.close()
    

And that's it.

