python对象列表转换为字典,将嵌套的Python对象转换为字典的最经济的方法是什么?...

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.

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??

I am hoping to do:

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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值