Friday, 30 March 2012

Python: Writing nested dictionaries to file

Best suggestion I could think of was using cPickle (if available).
try:
    import cPickle as pickle
except:
    import pickle

# nested DICTIONARY
data = { 'one': {'label': 'This is shot 001', 'start': 1, 'end': 10},
         'two': {'label': 'This is shot 002', 'start': 11, 'end': 25},
         'three': {'label': 'This is shot 003 - Needs Editing', 'start': 26, 'end': 50} }

# write to file with cPickle/pickle (as binary)
def ld_writeDicts(filePath,dict):
    f=open(filePath,'w')
    newData = pickle.dumps(dict, 1)
    f.write(newData)
    f.close()

ld_writeDicts('C:/Users/Lee/Desktop/test2.dta',data)

#############

# read file decoding with cPickle/pickle (as binary)
def ld_readDicts(filePath):
    f=open(filePath,'r')
    data = pickle.load(f)
    f.close()
    return data

# return dict data to new dict
newDataDict = ld_readDicts('C:/Users/Lee/Desktop/test2.dta')
# test nesting
print newDataDict['one']['label']
As you can see its very simple to use and very quick. There are loads of alternatives if you wanted a nicely arranged, readable file, including json:
import json

# nested DICTIONARY
data = { 'one': {'label': 'This is shot 001', 'start': 1, 'end': 10},
         'two': {'label': 'This is shot 002', 'start': 11, 'end': 25},
         'three': {'label': 'This is shot 003 - Needs Editing', 'start': 26, 'end': 50} }

# write to file with json encoding
def ld_writeDicts(filePath,dict):
    f=open(filePath,'w')
    newData = json.dumps(dict, sort_keys=True, indent=4)
    f.write(newData)
    f.close()

ld_writeDicts('C:/Users/Lee/Desktop/test',data)


# read file decoding with json
def ld_readDicts(filePath):
    f=open(filePath,'r')
    data = json.loads(f.read())
    f.close()
    return data

# return dict data to new dict
newDataDict = ld_readDicts('C:/Users/Lee/Desktop/test.dta')
# test nesting
print newDataDict['one']['label']

However im all for cPickle.

1 comment: