将namedtuple转换成字典 [英] Convert a namedtuple into a dictionary

查看:287
本文介绍了将namedtuple转换成字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a named tuple class in python

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

我想将Town实例转换成字典.我不希望它与城镇中字段的名称或数量严格相关.

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.

我无法将原始类定义更改为其他人的代码.因此,我需要以一个Town的实例为例,并将其转换为字典.

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:为此提供了一种_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的有据可查的方法,即与通常的约定不同在python中,方法名称的前划线不能阻止使用.连同添加到命名元组_make_replace_source_fields的其他方法一样,它具有下划线,仅用于尝试防止与可能的字段名称发生冲突.

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.

注意:对于2.7.5< python版本<在野外使用3.5.0代码时,您可能会看到以下版本:

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

一段时间以来,文档中提到_asdict已过时(请参见此处),建议使用内置方法 vars .那个建议现在已经过时了.为了修复与子类相关的一个错误再次删除了namedtuples上的__dict__属性. ="https://hg.python.org/cpython/rev/fa3ac31cfa44">此提交.

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.

这篇关于将namedtuple转换成字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆