问题描述
我在python中有一个命名的元组类
class Town(collections.namedtuple('Town', ['名称','人口','坐标','人口','首都','state_bird'])):# ...
我想将 Town 实例转换为字典.我不希望它与城镇中的字段名称或数量严格绑定.
有没有办法编写它,以便我可以添加更多字段,或者传入一个完全不同的命名元组并获取字典.
我无法像在其他人的代码中那样更改原始类定义.所以我需要取一个城镇的实例并将其转换为字典.
TL;DR:有一个方法 _asdict
为此提供.
以下是用法演示:
>>>fields = ['name', 'population', 'coordinates', 'capital', 'state_bird']>>>Town = collections.namedtuple('Town', fields)>>>funkytown = Town('funky', 300, '某处', 'lipps', 'chicken')>>>funkytown._asdict()OrderedDict([('name', 'funky'),('人口', 300),('坐标','某处'),('资本', '唇'),('state_bird', '鸡')])这是一个命名元组的记录方法,即不同于通常的约定在python中方法名称上的前导下划线不是为了阻止使用.与添加到命名元组的其他方法一起,_make
、_replace
、_source
、_fields
,它只有下划线尝试防止与可能的字段名称发生冲突.
注意:对于某些 2.7.5 <python版本<3.5.0 代码出来了,你可能会看到这个版本:
>>>瓦尔斯(时髦镇)OrderedDict([('name', 'funky'),('人口', 300),('坐标','某处'),('资本', '唇'),('state_bird', '鸡')])有一段时间文档提到 _asdict
已过时(请参阅 此处),并建议使用内置方法 vars.这个建议现在已经过时了.为了修复与子类化相关的一个错误,namedtuples 上的 __dict__
属性再次被被本次提交删除.
I have a named tuple class in python
class Town(collections.namedtuple('Town', [
'name',
'population',
'coordinates',
'population',
'capital',
'state_bird'])):
# ...
I'd like to convert Town instances into dictionaries. I don't want it to be rigidly tied to the names or number of the fields in a Town.
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.
I can not alter the original class definition as its in someone else's code. So I need to take an instance of a Town and convert it to a dictionary.
TL;DR: there's a method _asdict
provided for this.
Here is a demonstration of the usage:
>>> 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')])
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:
>>> vars(funkytown)
OrderedDict([('name', 'funky'),
('population', 300),
('coordinates', 'somewhere'),
('capital', 'lipps'),
('state_bird', 'chicken')])
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.
这篇关于将命名元组转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!