Writing and reading namedtuple into a file in python
Question: I need to write a datastructure stored as namedtuple to file and read it back
as a namedtuple in python.

Solutions here suggest using Json.load/s or pickle which write the variable as
json key-value pair in the form of strings.However, all my field
accesses/dereferences are of the form struct.key and not struct ["key"] which
is the way to access json values.and it is unfeasible to correct this in the
whole code.

I want to store this to a file because the struct is huge and takes a lot of
time to generate.


Answer: Since the standard JSON modules in Python generally use `dict` to work with
JSON objects, you need to convert to and from a `dict`.

For a little setup, let's say I've created this `namedtuple`:

    
    
    >>> from collections import namedtuple
    >>> import json
    >>> X = namedtuple('X', ['x', 'y', 'z'])
    >>> x = X(1,2,3)
    >>> x
    X(x=1, y=2, z=3)
    

1) Use `_asdict()` to convert to a `dict` that you can dump as JSON:

    
    
    >>> j = json.dumps(x._asdict())
    >>> j
    '{"x": 1, "y": 2, "z": 3}'
    

Now you have a JSON representation.

2) To get it back into an object, use `**` to convert a `dict` into keyword
arguments:

    
    
    >>> x2 = X(**json.loads(j))
    >>> x2
    X(x=1, y=2, z=3)
    

Done. You can of course read/write that JSON out to a file any way you wish.
(For example, the JSON modules have methods that work with files directly.)

