Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

from object list to dictionary then from dictionaty to object list

I need to translate a python list of objects formed with a my class Test
to a dictionary, because i need to save it on .txt file. Then i need to translate when i need it back to python list of objects because i need to update it, the result isnt what i expect. How can i do it? There is better way to do what i need? Cant find anything on web

class Test():
def __init__(self, var,var2):
    self.var = var
    self.var2 = var2


def dictionaryEncoder(self, contenuto):
    json_string = json.dumps([self.__dict__ for self in contenuto])
    return json_string

def dictionaryDecoder(self, letto):
    pyLetto = json.loads(letto, object_hook=lambda d: SimpleNamespace(**d))
    return pyLetto

The result the print of Python list:

[<__main__.Test object at 0x000001AB9E6217E0>, <__main__.Test object at 0x000001AB9E621840>, <__main__.Test object at 0x000001AB9E6338E0>, <__main__.Test object at 0x000001AB9E141A20>]

then translated to a dictionary:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{"var": 1, "var2": 11}, {"var": 2, "var2": 22}, {"var": 3, "var2": 33}, {"var": 4, "var2": 44}]

then translated to a dictionary then back in python list?:

[namespace(var=1, var2=11), namespace(var=2, var2=22), namespace(var=3, var2=33), namespace(var=4, var2=44)]

>Solution :

In dictionaryDecoder use:

def dictionaryDecoder(self, letto):
    return [Test(x['var'], x['var2']) for x in letto]

Input:

[{"var": 1, "var2": 11}, {"var": 2, "var2": 22}, {"var": 3, "var2": 33}, {"var": 4, "var2": 44}]

Output:

[<__main__.Test object at 0x7fcc5ea6d2e0>, <__main__.Test object at 0x7fcc5ea6d370>, <__main__.Test object at 0x7fcc5ea6d400>, <__main__.Test object at 0x7fcc5ea6d4f0>]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading