Home > OS >  from object list to dictionary then from dictionaty to object list
from object list to dictionary then from dictionaty to object list

Time:06-18

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:

[{"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)]

CodePudding user response:

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>]
  • Related