Home > Blockchain >  Export dictionary contents as code to declare dictionary
Export dictionary contents as code to declare dictionary

Time:09-13

I generated a dictionary of a list of tuples via HTML page scraping in an attempt to implement a scripting language. I would like to take that in-memory construct and generate Python code that initializes my dictionary to those values. I'm pretty sure I can write that up myself, but this isn't the first time I've encountered this situation, and it struck me that it's likely this has already been solved and might even be handled natively.

Example

mydict = {}
mydict ['item1'] = []
mydict ['item2'] = []
mydict ['item1'].append(('id', 11, 23))
mydict ['item1'].append(('id2', 21, 2))
mydict ['item1'].append(('id3', 13, 53))
mydict ['item1'].append(('id', 31, 23))
mydict ['item1'].append(('id2', 21, 9))
mydict ['item1'].append(('id3', -5, 7))

My actual data has several hundred items, so I'd prefer not to have to write them out.

CodePudding user response:

After a bit of fiddling on my own, I encountered pickle, and decided that it fit my case. I was leery at first, since it meant I couldn't readily tweak the data in the source code, but then I realized that, with the large number of values, I wouldn't want to try to tweak it by hand. I would still be interested in a way to easily take an existing structure, and generate corresponding source code to initialize it to those values, but for now, I am satisfied.

Writing out the structure:

with open('C:/temp/target.data', 'wb') as datafile:
    pickle.dump(mydict, datafile)

Loading it back in:

with open('c:/temp//target.data', 'rb') as datafile:
    mydict = pickle.load(datafile)
  • Related