I am working with a dictionary. From different resources, I understood that is comfortable to use pickle. I want to use pickle to save triples like: subject: predicate: object
, but later I want to load them and fill an array
Assuming, my code:
import pickle
file_name = 'fna.txt'
class DictClass:
def __init__(self, subj, predicate, obj ):
self.subj = subj
self.predicate = predicate
self.obj = obj
def __repr__(self):
return 'DictClass(%r, %r, %r)' % (self.subj, self.predicate, self.obj)
def __eq__(self, other):
return (self.subj == other.subj) and (self.predicate == other.predicate) and (self.obj == other.obj)
data = {'triple': DictClass(17,'subClassOf', 34), 'triple': DictClass(22,'subClassOf', 44)}
print('data:', data)
print('repr(data):', repr(data))
print("data == eval(repr(data), {'DictClass':DictClass})?:", data == eval(repr(data), {'DictClass':DictClass}))
# Load the dictionary back from the pickle file.
def ld_dict(fname):
reader = pickle.load(open(fname, 'rb'))
print(reader)
return True
# Save a dictionary into a pickle file.
def sv_dict(fname):
pickle.dump( data, open( fname, "wb" ) )
return True
if(sv_dict(file_name)):
print('File saved!')
if(ld_dict(file_name)):
print('File loaded!')
In generally, I want to save data in the dictionary and later load it and make some processing about it but I have a problem. I cannot access to the information into the loaded data. In function ld_dict
I was trying to read information and have results:
data: {'triple': DictClass(22, 'subClassOf', 44)}
repr(data): {'triple': DictClass(22, 'subClassOf', 44)}
data == eval(repr(data), {'DictClass':DictClass})?: True
File saved!
triple
File loaded!
How I can get information in the way like, for example, JSON. How to parse JSON I found here(How to parse json data in Python?). Also, I have seen this resource: how to save a dictionary in pickle Thank you for help