我在python中有一个命名的tuple类
class Town(collections.namedtuple('Town', [
'name',
'population',
'coordinates',
'population',
'capital',
'state_bird'])):
# ...
我想将Town实例转换成字典。我不希望它与城镇中字段的名称或数量严格相关。
有没有一种编写它的方式,这样我可以添加更多字段,或者传入完全不同的命名元组并获得字典。
我无法更改其他人代码中的原始类定义。因此,我需要以一个Town的实例为例,然后将其转换为字典。
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')])
这是namedtuple的documented method,即,与python中的常规约定不同[[方法名上的前划线不能阻止使用]。与添加到命名元组_make
,_replace
,_source
,_fields
的其他方法一起,其下划线仅用于尝试防止与可能的字段名称发生冲突。
注意:对于2.7.5 >>> vars(funkytown)
OrderedDict([('name', 'funky'),
('population', 300),
('coordinates', 'somewhere'),
('capital', 'lipps'),
('state_bird', 'chicken')])
一段时间以来,文档提到
_asdict
已过时(请参阅here),并建议使用内置方法vars。这个建议现在已经过时了。为了修复与子类化相关的a bug,__dict__
再次删除了命名元组上存在的this commit属性。
namedtuple
实例上有一个内置方法,_asdict
。如评论中所讨论,在某些版本上,_asdict
也将执行此操作,但是它显然高度依赖于构建细节,而vars()
应该可靠。在某些版本中,_asdict
被标记为已弃用,但注释表明从3.4开始不再是这种情况。
_asdict
属性按预期工作。__dict__
method也可以,但是我倾向于使用标准定义的统一属性api来代替本地化的非统一api。
$ python2.7_asdict
被视为dict是获取表示事物的字典的语义方法,(至少据我所知)。
积累一张主要的python版本和平台以及它们对# 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
的支持会很高兴,如上所述,我目前只有一个平台版本和两个python版本。
__dict__
| 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 |
def to_dict(model):
new_dict = {}
keys = model._fields
index = 0
for key in keys:
new_dict[key] = model[index]
index += 1
return new_dict
案例2:二维元组示例:DICT_ROLES [961]#将显示“后端程序员”
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"
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()