Skip to content
Advertisement

Pickle all variables

I”m looking for a way to pickle all the variables with their values in a sorted order. I’m trying the method below:

Expected result: Append value of va to totalList , then vb's value..and so on. And then dump the totalList to a pickle file.

import pickle
import time
import os
import re

v0 = ["r0", "hello","hello there","hi there","hi", "hey","good to see you"]
v1 = ["r1", "how are you", "how do you do","how are you doing", "how you doing"]
v2 = ["r2", "What's up" , "what is up" , "what's up bro"]
v10 = ['r10', 'who made you', 'who built you', 'who is your creator']


imports = "pickle","time","os","re"
totalList = []
for key in dir():
    if key.startswith("__") == 0 and key not in imports:
        print(globals()[key])
        totalList.append(globals()[key])
# print(totalList) # getting weird values

with open('queryList.pkl', 'wb') as f:
    pickle.dump(totalList, f)

I’m getting result like this:

>> ('pickle', 'time', 'os', 're')
>> []
>> ['r0', 'hello', 'hello there', 'hi there', 'hi', 'hey', 'good to see you']
>> ['r1', 'how are you', 'how do you do', 'how are you doing', 'how you doing']
>> ['r10', 'who made you', 'who built you', 'who is your creator']
>> ['r2', "What's up", 'what is up', "what's up bro"]

I want to get rid of the results ('pickle', 'time', 'os', 're') and [] and sort the result before appending to totalList or sort it before iteration.

Advertisement

Answer

Here’s a way to do what you want. You should ignore some variables you’re not interested in – specifically, imports and totalList.

ignore_list = [ "ignore_list", "totalList"]
totalList = []

for key in dir():
    if not key.startswith("__") and key not in ignore_list and type(globals()[key]) != type(pickle):
        print(key)
        totalList.append(globals()[key])

totalList = sorted(totalList, key=lambda x: int(x[0][1:]) )

The result is:

[['r0', 'hello', 'hello there', 'hi there', 'hi', 'hey', 'good to see you'],
 ['r1', 'how are you', 'how do you do', 'how are you doing', 'how you doing'],
 ['r2', "What's up", 'what is up', "what's up bro"],
 ['r10', 'who made you', 'who built you', 'who is your creator']]
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement