我有这个从 API 获得的嵌套字典。
response_body = \
{
u'access_token':u'SIF_HMACSHA256lxWT0K',
u'expires_in':86000,
u'name':u'Gandalf Grey',
u'preferred_username':u'gandalf',
u'ref_id':u'ab1d4237-edd7-4edd-934f-3486eac5c262',
u'refresh_token':u'eyJhbGciOiJIUzI1N',
u'roles':u'Instructor',
u'sub':{
u'cn':u'Gandalf Grey',
u'dc':u'7477',
u'uid':u'gandalf',
u'uniqueIdentifier':u'ab1d4237-edd7-4edd-934f-3486eac5c262'
}
}
我使用以下方法将其转换为 Python 对象:
class sample_token:
def __init__(self, **response):
self.__dict__.update(response)
并像这样使用它:
s = sample_token(**response_body)
在此之后,我可以使用 s.access_token
、s.name
等访问这些值。但是 c.sub
的值是也是一本字典。如何使用这种技术获取嵌套字典的值?即 s.sub.cn
返回 Gandalf Grey
。
最佳答案
也许是这样的递归方法-
>>> class sample_token:
... def __init__(self, **response):
... for k,v in response.items():
... if isinstance(v,dict):
... self.__dict__[k] = sample_token(**v)
... else:
... self.__dict__[k] = v
...
>>> s = sample_token(**response_body)
>>> s.sub
<__main__.sample_token object at 0x02CEA530>
>>> s.sub.cn
'Gandalf Grey'
我们遍历响应中的每个 key:value
对,如果 value 是一个字典,我们为其创建一个 sample_token 对象并将该新对象放入 __dict__()
.
关于python - 将嵌套字典转换为 Python 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31643861/