python - Pickling multiple dictionaries -


so i'm new python , i'll asking many noob questions throughout learning process (if haven't been asked/answered of course).

one question have if there way save multiple dictionaries 1 text file using pickle, or if each individual dictionary has saved it's own separate file. example, if want create program manage web accounts, each account having variety of arbitrary keys/values, can save these individual accounts 1 archive separate dictionaries?

thanks in advance, , noob appreciate example code and/or suggestions.

one quick solution place both dictionaries in list, pickle list.

here example writes out binary file.

    import cpickle pkl      myfirstdict = { "hat": 7, "carpet": 5 }     myseconddict = { "syrup":15, "yogurt": 18 }      mydicts = [myfirstdict, myseconddict]      pkl.dump( mydicts, open( "mydicts.p", "wb" ) ) 

here 1 loads it.

    import cpickle pkl      mydicts = pkl.load( open ("mydicts.p", "rb") ) 

if need file human readable, consider writing out regular text file instead. warned, far less efficient , leaves data exposed web account data.

    myfirstdict = { "hat": 7, "carpet": 5 }     myseconddict = { "syrup":15, "yogurt": 18 }      mydicts = [myfirstdict, myseconddict]      outputfile = open( "mydicts.txt", "w")     outputfile.write(str(mydicts))     outputfile.flush()     outputfile.close() 

and read in...

    import ast      inputfile = open( "mydicts.txt", "r")     lines = inputfile.readlines()      objects = []     line in lines:         objects.append( ast.literal_eval(line) )      mydicts = objects[0] 

references:

// reference pickle http://wiki.python.org/moin/usingpickle

// source text-to-object solution python convert string object dictionary


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -