Oin Oin - 22 days ago 6
Python Question

_asdict in Python 3 namedtuple subclass returns empty dictionary

How can I use

_asdict
from a Python 3 subclass of
namedtuple
?

This is what I've tried:

class A(namedtuple('B', 'c')):
pass

a = A(3)

a._asdict()
{}


This works fine in Python 2 and returns:

OrderedDict([('c', 3)])

Answer

Ok, this was listed as a bug in Issue 24931 and fixed in version 3.5.2 if I am not mistaken.

In my current version of Python 3.5.2 this performs as expected:

a._asdict()
Out[7]: OrderedDict([('c', 3)])

In short, consider updating to 3.5.1+. If you cannot, implementing _asdict yourself, as is stated in a message on the issue tracker, seems like a viable alternative:

from collections import namedtuple, OrderedDict

class A(namedtuple('B', 'c')):
    def _asdict(self):
        return OrderedDict(zip(self._fields, self))