Python Forum
convert a named tuple to a dictionary - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: convert a named tuple to a dictionary (/thread-36786.html)

Pages: 1 2


convert a named tuple to a dictionary - Skaperen - Mar-30-2022

is there a better way (like a built-in way) to convert a named tuple to a dictionary?

def named_tuple_to_dict(t):
    return {n:getattr(t,n) for n in dir(t) if n[0] != '_'}



RE: convert a named tuple to a dictionary - deanhystad - Mar-30-2022

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p._asdict())

fields = {field:getattr(p, field) for field in p._fields}
print(fields)
Output:
{'x': 1, 'y': 2} {'x': 1, 'y': 2}



RE: convert a named tuple to a dictionary - buran - Mar-30-2022

There is dedicated method for that - somenamedtuple._asdict()


RE: convert a named tuple to a dictionary - DeaD_EyE - Mar-30-2022

The _asdict method does the following:
return _dict(_zip(self._fields, self))
It should be the way how you convert it to a dict.

You could write your function like this:
from __future__ import annotations
# for compatibility

from collections import namedtuple as NamedTuple
# I hate classes, which do not follow the PythonNamingScheme
# Instead, I rename this class to NamedTuple.
from typing import Any
# Just for the return type of values
# we don't know which types the values have
# but the keys are str

def asdict(nt: NamedTuple) -> dict[str, Any]:
    return dict(zip(nt._fields, nt))



MyResult = NamedTuple("MyResult", "a b c")

result = MyResult(1,2,3)
result_dict = asdict(result)

# similar to

keys = ("A", "B", "C")
values = (1, 2, 3)
# strict=True will fail if keys have a different length than
# values. It was introducted with Python 3.10 I think
# will raise a value error if the length didn't match
mapping = dict(zip(keys, values, strict=True))



RE: convert a named tuple to a dictionary - buran - Mar-30-2022

Why write function to mimic readily available method?


RE: convert a named tuple to a dictionary - Skaperen - Mar-30-2022

(Mar-30-2022, 09:18 AM)buran Wrote: Why write function to mimic readily available method?
i agree. that's why i ask. i did read of "_asdict". but it was not working in my 3.6.9. so i needed to find a way that worked.


RE: convert a named tuple to a dictionary - deanhystad - Mar-30-2022

That information should have been in the original post.


RE: convert a named tuple to a dictionary - Skaperen - Mar-30-2022

(Mar-30-2022, 08:10 PM)deanhystad Wrote: That information should have been in the original post.
i keep posts minimal until asked. i thought 3.6.9 was too old. i've run into the issue of it being too old many times, before. i was looking for a pan-version solution. i still don't know which version "._addict()" was introduced. do you?

i keep posts minimal until asked. they can become very large if i try to add every piece of info anyone may want to know. when large like that they tend to be skipped over.

i'll try to find my code that tested _asdict().


RE: convert a named tuple to a dictionary - deanhystad - Mar-30-2022

It would have been valuable knowing that you tried _asdict() and it didn't work for 3.69.


RE: convert a named tuple to a dictionary - Skaperen - Mar-31-2022

(Mar-30-2022, 09:09 AM)DeaD_EyE Wrote: The _asdict method does the following:
    return _dict(_zip(self._fields, self))
It should be the way how you convert it to a dict.
that is definitely simpler than what i came up with, even without the conditional in mine, although i don't know if "self" can be substituted with "t" to fit in for a short and sweet function.

edit:

i'm still looking for that code where _asdict failed (an unknown attribute error).