将namedtuple转换成字典

编程入门 行业动态 更新时间:2024-10-25 22:33:59
本文介绍了将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__属性. ="hg.python/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转换成字典

本文发布于:2023-06-10 02:01:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/606241.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换成   字典   namedtuple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!