python命名元组到字典

2024-05-12 17:24:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我想把城镇实例转换成字典。我不想把它和一个镇上的田地的名称或数量绑在一起。

有没有一种方法可以让我添加更多的字段,或者传入一个完全不同的命名元组并得到一个字典。

我不能在其他人的代码中更改原始类定义。所以我需要以一个城镇为例,把它转换成一本字典。


Tags: 实例name字典namedtuple命名collectionsclass元组
3条回答

namedtuple实例上有一个内置的方法,这个^{}

正如评论中所讨论的,在某些版本上,vars()也会这样做,但它显然高度依赖于构建细节,而_asdict应该是可靠的。在某些版本中,_asdict被标记为已弃用,但注释表明,从3.4开始不再是这种情况。

在Ubuntu 14.04lts版本的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

看到asdict是获得表示soemthing的字典的语义方法(至少据我所知)。


如果能积累一个包含主要python版本和平台及其对__dict__的支持的表,那就太好了,目前我只有一个平台版本和两个python版本,如上面所述。

| Platform                      | PyVer     | __dict__ | _asdict |
| --------------------------    | --------- | -------- | ------- |
| Ubuntu 14.04 LTS              | Python2.7 | yes      | yes     |
| Ubuntu 14.04 LTS              | Python3.4 | yes      | yes     |
| CentOS Linux release 7.4.1708 | Python2.7 | no       | yes     |
| CentOS Linux release 7.4.1708 | Python3.4 | no       | yes     |
| CentOS Linux release 7.4.1708 | Python3.6 | no       | yes     |

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版本<;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删除。

相关问题 更多 >