python将元组命名为字典

我有一个在python中命名的元组类

class Town(collections.namedtuple('Town', [ 'name', 'population', 'coordinates', 'population', 'capital', 'state_bird'])): # ... 

我想做的是把它变成一本字典。 我承认Python不是我更强大的语言之一。 关键是,我不希望它与我所拥有的领域的名字或数字有严格的联系。

有没有办法写它,使我可以添加更多的字段,或传递一个完全不同的命名元组,并获得一本字典。

编辑:我不能改变原来的类定义为在别人的代码。 所以我需要拿一个城市的实例,并将其转换为字典。

TL; DR: _asdict提供了一个方法_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')]) 

这是namedtuples的一个文档化的方法 ,也就是说不像python中惯用的约定, 方法名的前面的下划线不会阻止使用 。 除了添加到_make的其他方法, _make_replace_source_fields ,它只有下划线才能尝试和防止与可能的字段名称冲突。


注意:对于一些2.7.5 <python版本<3.5.0的代码,你可能会看到这个版本:

 >>> vars(funkytown) OrderedDict([('name', 'funky'), ('population', 300), ('coordinates', 'somewhere'), ('capital', 'lipps'), ('state_bird', 'chicken')]) 

有一段时间,文档中提到_asdict已经过时了(见这里 ),并build议使用内置的方法variables 。 那个build议现在已经过时了。 为了修复与子类相关的错误 ,已经在namedtuples上出现的__dict__属性再次被这个提交删除。

有一个内置的方法在这个_asdict这个_asdict实例。

正如在评论中所讨论的那样,在一些版本中, vars()也会这样做,但显然高度依赖于构build细节,而_asdict应该是可靠的。 在一些版本中, _asdict被标记为已弃用,但是评论表明,这已经不是3.4的情况。

在Ubuntu 14 LTS版本的python2.7和python3.4上,__dict__属性按预期工作。 _asdict 方法也有效,但我倾向于使用标准定义的,统一的属性api,而不是本地化的非统一API。

$ python2.7

 # Works on: # Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 # Python 3.4.3 (default, Oct 14 2015, 20:28:29) [GCC 4.8.4] on linux import collections Color = collections.namedtuple('Color', ['r', 'g', 'b']) red = Color(r=256, g=0, b=0) # Access the namedtuple as a dict print(red.__dict__['r']) # 256 # Drop the namedtuple only keeping the dict red = red.__dict__ print(red['r']) #256 

看作是字典是得到一个代表某事的字典的语义方法,(至less据我所知)。


积累一个主要的python版本和平台以及它们对__dict__的支持是很好的,目前我只有一个平台版本和两个python版本。

 | Platform | PyVer | __dict__ | _asdict | | ------------- | --------- | -------- | ------- | | Ubuntu 14 LTS | Python2.7 | yes | yes | | Ubuntu 14 LTS | Python3.4 | yes | yes | 

Python 3.将任何字段分配给字典,作为字典所需的索引,我使用“name”。

 import collections Town = collections.namedtuple("Town", "name population coordinates capital state_bird") town_list = [] town_list.append(Town('Town 1', '10', '10.10', 'Capital 1', 'Turkey')) town_list.append(Town('Town 2', '11', '11.11', 'Capital 2', 'Duck')) town_dictionary = {t.name: t for t in town_list}