将嵌套的Python对象转换为字典的最经济的方法是什么? [英] What is the most economical way to convert nested Python objects to dictionaries?

查看:533
本文介绍了将嵌套的Python对象转换为字典的最经济的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些SQLAlchemy对象,其中包含更多SQLAlchemy对象的列表,依此类推(大约5个级别).我希望将所有对象都转换成字典.

I have some SQLAlchemy objects which contain lists of more SQLAlchemy objects, and so on (for about 5 levels). I wish to convert all the objects to dictionaries.

我可以使用__dict__属性将对象转换为字典,没问题.但是,我在寻找最佳方法来转换所有嵌套对象时也遇到了麻烦,而不必显式地完成每个级别.

I can convert an object to a dictionary by using the __dict__ property, no problem. However, I'm having trouble figuring out the best way to convert all the nested objects as well, without having to do each level explicitly.

到目前为止,这是我能想到的最好的方法,但是不能正确地递归.经过一遍后,它基本上会中断,因此我的逻辑显然有问题.您能看到问题在哪里吗?

So far, this is the best I can come up with, but it doesn't recurse properly. It basically breaks after one pass, so there's clearly something wrong with my logic. Can you see what's wrong with it??

我希望这样做:

all_dict = myDict(obj.__dict__)

def myDict(d):
    for k,v in d.items():
        if isinstance(v,list):
            d[k] = [myDict(i.__dict__) for i in v]
        else:
            d[k] = v
    return d

推荐答案

我不确定我是否完全了解您想要的内容-但是如果知道了,此函数可以完成您想要的操作: 它确实对对象的属性进行递归搜索,产生嵌套的字典+列表结构,其终点是不具有__dict__属性的python对象-在SQLAlchemy的情况下,它很可能是基本的Python类型,例如数字和字符串. (如果失败,则替换"hasattr dict"测试以使事情更明智,应会根据您的需要修复代码.

I am not sure if I understood exactly what you want - but if I got, this function can do what you want: It does search recursively on an object's attributes, yielding a nested dictionary + list structure, with the ending points being python objects not having a __dict__ attribute - which in SQLAlchemy's case are likely to be basic Python types like numbers and strings. (If that fails, replacing the "hasattr dict" test for soemthing more sensible should fix the code for your needs.

def my_dict(obj):
    if not  hasattr(obj,"__dict__"):
        return obj
    result = {}
    for key, val in obj.__dict__.items():
        if key.startswith("_"):
            continue
        element = []
        if isinstance(val, list):
            for item in val:
                element.append(my_dict(item))
        else:
            element = my_dict(val)
        result[key] = element
    return result

这篇关于将嵌套的Python对象转换为字典的最经济的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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