TL;DR:有一个方法_asdict
为此提供的。
下面是用法演示:
>>> from collections import namedtuple
>>> fields = ['name', 'population', 'coordinates', 'capital', 'state_bird']
>>> Town = namedtuple('Town', fields)
>>> funkytown = Town('funky', 300, 'somewhere', 'lipps', 'chicken')
>>> funkytown._asdict()
{'name': 'funky',
'population': 300,
'coordinates': 'somewhere',
'capital': 'lipps',
'state_bird': 'chicken'}
这是一个记录方法 https://docs.python.org/3/library/collections.html#collections.somenamedtuple._asdict命名元组,即与 python 中通常的约定不同方法名称上的前导下划线并不阻止使用。与添加到命名元组的其他方法一起,_make
, _replace
, _source
, _fields
,它有下划线只是为了尝试防止与可能的字段名称发生冲突。
Note:对于一些 2.7.5
>>> vars(funkytown)
OrderedDict([('name', 'funky'),
('population', 300),
('coordinates', 'somewhere'),
('capital', 'lipps'),
('state_bird', 'chicken')])
有一段时间,文档提到了这一点_asdict
已过时(参见here https://docs.python.org/3.3/library/collections.html#collections.somenamedtuple._asdict),并建议使用内置方法vars https://docs.python.org/3/library/functions.html#vars。这个建议现在已经过时了。为了修复a bug http://bugs.python.org/issue24931与子类化相关,__dict__
存在于命名元组上的属性再次被删除这次提交 https://hg.python.org/cpython/rev/fa3ac31cfa44.