Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store a dictionary in a file for later retrieval

I've had a search around but can't find anything regarding this...

I'm looking for a way to save a dictionary to file and then later be able to load it back into a variable at a later date by reading the file.

The contents of the file don't have to be "human readable" it can be as messy as it wants.

Thanks - Hyflex

EDIT

import cPickle as pickle

BDICT = {}

## Automatically generated START
name = "BOB"
name_title = name.title()
count = 5
BDICT[name_title] = count

name = "TOM"
name_title = name.title()
count = 5
BDICT[name_title] = count

name = "TIMMY JOE"
name_title = name.title()
count = 5
BDICT[name_title] = count
## Automatically generated END

if BDICT:
    with open('DICT_ITEMS.txt', 'wb') as dict_items_save:
        pickle.dump(BDICT, dict_items_save)

BDICT = {} ## Wiping the dictionary

## Usually in a loop
firstrunDICT = True

if firstrunDICT:
    with open('DICT_ITEMS.txt', 'rb') as dict_items_open:
        dict_items_read = dict_items_open.read()
        if dict_items_read:
            BDICT = pickle.load(dict_items_open)
            firstrunDICT = False
            print BDICT

Error:

Traceback (most recent call last):
  File "C:\test3.py", line 35, in <module>
    BDICT = pickle.load(dict_items_open)
EOFError
like image 211
Ryflex Avatar asked Jun 26 '13 14:06

Ryflex


People also ask

Can you save a Python dictionary to file?

How to make python save a dictionary to a file. These are small programs that allows you to create a dictionary and then, when running the program, it will create a file that contains the data in the original dictionary. We can save it to one of these formats: Comma seperated value file (.

How do you put a dictionary in a zip file?

To create a dictionary from two sequences, use the dict() and zip() method. The dict(zip(keys, values)) needs the one-time global lookup each for dict and zip. Still, it doesn't create any needless intermediary data structures or deal with local lookups in function applications.


1 Answers

Two functions which create a text file for saving a dictionary and loading a dictionary (which was already saved before) for use again.

import pickle

def SaveDictionary(dictionary,File):
    with open(File, "wb") as myFile:
        pickle.dump(dictionary, myFile)
        myFile.close()

def LoadDictionary(File):
    with open(File, "rb") as myFile:
        dict = pickle.load(myFile)
        myFile.close()
        return dict

These functions can be called through :

SaveDictionary(mylib.Members,"members.txt") # saved dict. in a file
members = LoadDictionary("members.txt")     # opened dict. of members
like image 129
user5217748 Avatar answered Nov 08 '22 18:11

user5217748