我在python中有一个命名的tuple类

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

我想将Town实例转换为字典。我不希望它严格地绑定到Town中的字段名称或数量。

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

我不能改变原来的类定义,因为它在别人的代码。因此,我需要取一个Town实例并将其转换为字典。


当前回答

在Ubuntu 14.04 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

Seeing as dict是语义上获取表示某物的字典的方法(至少就我所知)。


收集一个主要的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     |

其他回答

在namedtuple实例上有一个内置的方法,_asdict。

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

案例#1:一维元组

TUPLE_ROLES = (
    (912,"Role 21"),
    (913,"Role 22"),
    (925,"Role 23"),
    (918,"Role 24"),
)


TUPLE_ROLES[912]  #==> Error because it is out of bounce. 
TUPLE_ROLES[  2]  #==> will show Role 23.
DICT1_ROLE = {k:v for k, v in TUPLE_ROLES }
DICT1_ROLE[925] # will display "Role 23" 

案例2:二维元组 示例:DICT_ROLES[961] #将显示'后端程序员'

NAMEDTUPLE_ROLES = (
    ('Company', ( 
            ( 111, 'Owner/CEO/President'), 
            ( 113, 'Manager'),
            ( 115, 'Receptionist'),
            ( 117, 'Marketer'),
            ( 119, 'Sales Person'),
            ( 121, 'Accountant'),
            ( 123, 'Director'),
            ( 125, 'Vice President'),
            ( 127, 'HR Specialist'),
            ( 141, 'System Operator'),
    )),
    ('Restaurant', ( 
            ( 211, 'Chef'), 
            ( 212, 'Waiter/Waitress'), 
    )),
    ('Oil Collector', ( 
            ( 211, 'Truck Driver'), 
            ( 213, 'Tank Installer'), 
            ( 217, 'Welder'),
            ( 218, 'In-house Handler'),
            ( 219, 'Dispatcher'),
    )),
    ('Information Technology', ( 
            ( 912, 'Server Administrator'),
            ( 914, 'Graphic Designer'),
            ( 916, 'Project Manager'),
            ( 918, 'Consultant'),
            ( 921, 'Business Logic Analyzer'),
            ( 923, 'Data Model Designer'),
            ( 951, 'Programmer'),
            ( 953, 'WEB Front-End Programmer'),
            ( 955, 'Android Programmer'),
            ( 957, 'iOS Programmer'),
            ( 961, 'Back-End Programmer'),
            ( 962, 'Fullstack Programmer'),
            ( 971, 'System Architect'),
    )),
)

#Thus, we need dictionary/set

T4 = {}
def main():
    for k, v in NAMEDTUPLE_ROLES:
        for k1, v1 in v:
            T4.update ( {k1:v1}  )
    print (T4[961]) # will display 'Back-End Programmer'
    # print (T4) # will display all list of dictionary

main()

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')])

这是一个有文档记录的namedtuples方法,也就是说,与python中通常的约定不同,方法名称上的前导下划线并不是为了阻止使用。与其他添加到命名元组_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已经过时了(见这里),并建议使用内置方法vars。这个建议现在已经过时了;为了修复与子类化相关的错误,在namedtuples上出现的__dict__属性再次被此提交删除。

通常_asdict()返回OrderedDict。这是如何从OrderedDict转换为常规dict


town = Town('funky', 300, 'somewhere', 'lipps', 'chicken')
dict(town._asdict())

输出将是

{'capital': 'lipps',
 'coordinates': 'somewhere',
 'name': 'funky',
 'population': 300,
 'state_bird': 'chicken'}

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}