递归地将python对象图转换为字典 [英] Recursively convert python object graph to dictionary

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

问题描述

我正在尝试将数据从简单的对象图转换为字典.我不需要类型信息或方法,也不需要能够再次将其转换回对象.

I'm trying to convert the data from a simple object graph into a dictionary. I don't need type information or methods and I don't need to be able to convert it back to an object again.

我发现了这个关于从对象的字段创建字典的问题,但它不会递归执行.

I found this question about creating a dictionary from an object's fields, but it doesn't do it recursively.

作为 Python 的新手,我担心我的解决方案可能很丑陋,或者不符合 Python 风格,或者以某种晦涩的方式被破坏,或者只是普通的 NIH.

Being relatively new to python, I'm concerned that my solution may be ugly, or unpythonic, or broken in some obscure way, or just plain old NIH.

在我尝试使用列表和字典之前,我的第一次尝试似乎有效,而且似乎更容易检查传递的对象是否具有内部字典,如果没有,则将其视为一个值(而不是执行所有操作)那就是实例检查).我之前的尝试也没有递归到对象列表中:

My first attempt appeared to work until I tried it with lists and dictionaries, and it seemed easier just to check if the object passed had an internal dictionary, and if not, to just treat it as a value (rather than doing all that isinstance checking). My previous attempts also didn't recurse into lists of objects:

def todict(obj):
    if hasattr(obj, "__iter__"):
        return [todict(v) for v in obj]
    elif hasattr(obj, "__dict__"):
        return dict([(key, todict(value)) 
            for key, value in obj.__dict__.iteritems() 
            if not callable(value) and not key.startswith('_')])
    else:
        return obj

这似乎工作得更好,不需要例外,但我仍然不确定这里是否有案例,我不知道它在哪里下降.

This seems to work better and doesn't require exceptions, but again I'm still not sure if there are cases here I'm not aware of where it falls down.

任何建议将不胜感激.

推荐答案

我自己的尝试和从 Anurag Uniyal 和 Lennart Regebro 的答案中得出的线索的合并最适合我:

An amalgamation of my own attempt and clues derived from Anurag Uniyal and Lennart Regebro's answers works best for me:

def todict(obj, classkey=None):
    if isinstance(obj, dict):
        data = {}
        for (k, v) in obj.items():
            data[k] = todict(v, classkey)
        return data
    elif hasattr(obj, "_ast"):
        return todict(obj._ast())
    elif hasattr(obj, "__iter__") and not isinstance(obj, str):
        return [todict(v, classkey) for v in obj]
    elif hasattr(obj, "__dict__"):
        data = dict([(key, todict(value, classkey)) 
            for key, value in obj.__dict__.items() 
            if not callable(value) and not key.startswith('_')])
        if classkey is not None and hasattr(obj, "__class__"):
            data[classkey] = obj.__class__.__name__
        return data
    else:
        return obj

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

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