I have a named tuple class in python
class Town(collections.namedtuple('Town', [
'name',
'population',
'coordinates',
'population',
'capital',
'state_bird'])):
# ...
What I'd like to do is turn this into a dictionary. I'll admit python is not one of my stronger languages. The key is that I dont want it to be rigidly tied to the name or numbers of the fields I have.
Is there a way to write it such that I could add more fields, or pass an entirely different named tuple in and get a dictionary.
Edit: I cant not alter the original class definition as its in someone elses code. So I need to take an instance of a Town and convert it to a dictionary.
On Ubuntu 14.04 LTS versions of python2.7 and python3.4 the
__dict__
property worked as expected. The_asdict
method also worked, but I'm inclined to use the standards-defined, uniform, property api instead of the localized non-uniform api.$ python2.7
Seeing as dict is the semantic way to get a dictionary representing soemthing, (at least to the best of my knowledge).
It would be nice to accumulate a table of major python versions and platforms and their support for
__dict__
, currently I only have one platform version and two python versions as posted above.Python 3. Allocate any field to the dictionary as the required index for the dictionary, I used 'name'.
There's a built in method on
namedtuple
instances for this,_asdict
.As discussed in the comments, on some versions
vars()
will also do it, but it's apparently highly dependent on build details, whereas_asdict
should be reliable. In some versions_asdict
was marked as deprecated, but comments indicate that this is no longer the case as of 3.4.TL;DR: there's a method
_asdict
provided for this.Here is a demonstration of the usage:
This is a documented method of namedtuples, i.e. unlike the usual convention in python the leading underscore on the method name isn't there to discourage use. Along with the other methods added to namedtuples,
_make
,_replace
,_source
,_fields
, it has the underscore only to try and prevent conflicts with possible field names.Note: For some 2.7.5 < python version < 3.5.0 code out in the wild, you might see this version:
For a while the documentation had mentioned that
_asdict
was obsolete (see here), and suggested to use the built-in method vars. That advice is now outdated; in order to fix a bug related to subclassing, the__dict__
property which was present on namedtuples has again been removed by this commit.