TL; DR:有一个为此提供的方法_asdict。
这里是一个示范的用法:
>>> fields = ['name', 'population', 'coordinates', 'capital', 'state_bird']
>>> Town = collections.namedtuple('Town', fields)
>>> funkytown = Town('funky', 300, 'somewhere', 'lipps', 'chicken')
>>> funkytown._asdict()
OrderedDict([('name', 'funky'),
('population', 300),
('coordinates', 'somewhere'),
('capital', 'lipps'),
('state_bird', 'chicken')])
这是一个documented method的namedtuples,即不同于通常的约定在python方法名称的前导下划线不是阻止使用。除了添加到namedtuples,_make,_replace,_source,_fields的其他方法,它有下划线只能尝试和防止与可能的字段名称冲突。
注:对于一些2.7.5 python version< 3.5.0代码在野外,你可能会看到这个版本:
>>> vars(funkytown)
OrderedDict([('name', 'funky'),
('population', 300),
('coordinates', 'somewhere'),
('capital', 'lipps'),
('state_bird', 'chicken')])
一段时间文档已经提到_asdict已过时(见here),并建议使用内置方法vars.这个建议现在已经过时了;为了修复与子类化相关的a bug,在namedtuples上存在的__dict__属性再次被this commit删除。