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.
JavaScript
x
22
22
1
import pickle
2
import time
3
import os
4
import re
5
6
v0 = ["r0", "hello","hello there","hi there","hi", "hey","good to see you"]
7
v1 = ["r1", "how are you", "how do you do","how are you doing", "how you doing"]
8
v2 = ["r2", "What's up" , "what is up" , "what's up bro"]
9
v10 = ['r10', 'who made you', 'who built you', 'who is your creator']
10
11
12
imports = "pickle","time","os","re"
13
totalList = []
14
for key in dir():
15
if key.startswith("__") == 0 and key not in imports:
16
print(globals()[key])
17
totalList.append(globals()[key])
18
# print(totalList) # getting weird values
19
20
with open('queryList.pkl', 'wb') as f:
21
pickle.dump(totalList, f)
22
I’m getting result like this:
JavaScript
1
7
1
>> ('pickle', 'time', 'os', 're')
2
>> []
3
>> ['r0', 'hello', 'hello there', 'hi there', 'hi', 'hey', 'good to see you']
4
>> ['r1', 'how are you', 'how do you do', 'how are you doing', 'how you doing']
5
>> ['r10', 'who made you', 'who built you', 'who is your creator']
6
>> ['r2', "What's up", 'what is up', "what's up bro"]
7
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
.
JavaScript
1
10
10
1
ignore_list = [ "ignore_list", "totalList"]
2
totalList = []
3
4
for key in dir():
5
if not key.startswith("__") and key not in ignore_list and type(globals()[key]) != type(pickle):
6
print(key)
7
totalList.append(globals()[key])
8
9
totalList = sorted(totalList, key=lambda x: int(x[0][1:]) )
10
The result is:
JavaScript
1
5
1
[['r0', 'hello', 'hello there', 'hi there', 'hi', 'hey', 'good to see you'],
2
['r1', 'how are you', 'how do you do', 'how are you doing', 'how you doing'],
3
['r2', "What's up", 'what is up', "what's up bro"],
4
['r10', 'who made you', 'who built you', 'who is your creator']]
5