Convert namespace to dict object

I have a namespace and I want to convert the whole namespace to a dict object without concerning with the actual member names. Here’s what I’m doing now:

{% set ns=namespace(x=5,y=10,z=15) %}
...
{# do thing to accumulate values in the namespace members, say inside a for loop #}
{% set ns.x = ns.x + ... %}
...
{{ ns }} {# yields the string "<Namespace {'x': 5, 'y': 10, 'z': 15}>" #}

{% set d = ((ns|string)[11:][:-1]) | replace("'", "\"") | from_json %}
{{ d }} {# yields dict object having x,y,z }#
{{ d.x }} {# yields 5 #}

so that formula strips the text down and converts to json and then parses that to dict object.

Is there maybe a simpler way, e.g. without going through text and parsing json?

(I’ve tried dict(ns) and ns | dict to no avail.)

Thanks in advance!


Sometimes I add new members to the namespace (sometimes needed sometimes just for debugging). When I convert the namespace to a dictionary (as per my above), I can return that dictionary from a script, without some construct that mentions each member by name. (e.g. without doing {{ { 'x': ns.x, 'y': ns.y, 'z': ns.z } }}, which would seems silly if we could simply iterate on the namespace or convert directly to dict.)

Not sure about the reason/choice of the above ns but this may help?

{% set ns = namespace(d=dict(x=5, y=10, z=15)) %}

{{ ns.d }}   
{{ ns.d.x }}

It would help to understand what your goal is. Although a namespace isn’t a dictionary, it can be used like one in many cases. If your goal is that you want to access the items, you can already do that with a native namespace:

{% set ns=namespace(x=5,y=10,z=15) %}
...
{{ ns.x }} {# yields 5 #}