python命名元组到字典 [英] python Named tuple to dictionary

查看:168
本文介绍了python命名元组到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a named tuple class in python

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

我想做的是将其转换为字典。我会承认python不是我更强大的语言之一。关键是我不希望它与我所拥有的字段的名称或数字紧密相连。

What I'd like to do is turn this into a dictionary. I'll admit python is not one of my stronger languages. The key is that I dont want it to be rigidly tied to the name or numbers of the fields I have.

有没有办法写这个,以便我可以添加更多的字段,或者传递一个完全不同的命名元组,并获得一个字典。

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.

编辑:我不能改变原来的类定义,因为它在某人的编码中。所以我需要一个城镇的实例,并将其转换成一个字典。

I cant not alter the original class definition as its in someone elses code. So I need to take an instance of a Town and convert it to a dictionary.

推荐答案

为此提供了一种方法 _asdict

以下是使用方法的演示:

Here is a demonstration of the usage:

>>> 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 通常的惯例中,方法名称的前导下划线不会阻止使用。除了添加到namedtuples的其他方法, _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 已经过时(请参阅这里),并建议使用内置方法瓦尔。这个建议现在已经过时了;为了修复与子类相关的一个错误,这是 __ dict __ 属性在此提交中已经删除了namedtuples上的内容。

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.

这篇关于python命名元组到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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