Python Forum
convert a named tuple to a dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
convert a named tuple to a dictionary
#1
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] != '_'}
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
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}
Reply
#3
There is dedicated method for that - somenamedtuple._asdict()
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
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))
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
Why write function to mimic readily available method?
ndc85430 likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
(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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#7
That information should have been in the original post.
ndc85430 likes this post
Reply
#8
(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().
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#9
It would have been valuable knowing that you tried _asdict() and it didn't work for 3.69.
ndc85430 likes this post
Reply
#10
(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).
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to convert tuple value into string mg24 2 2,357 Oct-06-2022, 08:13 AM
Last Post: DeaD_EyE
  convert List with dictionaries to a single dictionary iamaghost 3 2,878 Jan-22-2021, 03:56 PM
Last Post: iamaghost
Sad Convert python list to dictionary akanowhere 6 3,469 Dec-27-2020, 09:26 PM
Last Post: Pedroski55
  code with no tuple gets : IndexError: tuple index out of range Aggam 4 2,843 Nov-04-2020, 11:26 AM
Last Post: Aggam
  Updating dictionary with tuple Mark17 2 2,017 Aug-06-2020, 02:59 PM
Last Post: Mark17
  how to get the keys in a named tuple Skaperen 5 10,864 Mar-25-2020, 09:51 PM
Last Post: Skaperen
  How to get first line of a tuple and the third item in its tuple. Need Help, Anybody? SukhmeetSingh 5 3,215 May-21-2019, 11:39 AM
Last Post: avorane
  Convert List of Dictionary to dictionary of dictionary list in python kk230689 2 51,897 Apr-27-2019, 03:13 AM
Last Post: perfringo
  Converting List of 3 Element Tuple to Dictionary fooikonomou 11 5,848 Jan-14-2019, 09:51 AM
Last Post: perfringo
  unable to convert text file in dictionary purnima1 6 4,343 Apr-02-2018, 07:44 AM
Last Post: purnima1

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020