Python如何地柜解析这种数据类型,data__key__hello = "world"
本文介绍了Python如何地柜解析这种数据类型,data__key__hello = "world"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
比如有这么一个字典:
{
'data__key_hello': "world",
'data__key_bar': "foo",
'data__a': "b",
'b': 'c',
}
转换之后变成
{
'data': {
'key': {
'hello': 'world',
'bar': 'foo'
},
'a': 'b',
},
'b': 'c'
}
就是以下划线进行一个分割
解决方案
# coding: utf-8
def parse_dict(obj={}):
result = {}
for key in obj:
value = obj[key]
parse_key_value(key, value, result)
return result
def parse_key_value(key, value, result={}):
if not key:
return
head = ''
while 1:
head, _, tail = key.partition('_')
if head:
break
key = tail
if head not in result:
if tail:
result[head] = {}
else:
result[head] = value
return
parse_key_value(tail, value, result[head])
obj = {
'data__key_hello': "world",
'data__key_bar': "foo",
'data__a': "b",
'b': 'c',
}
print parse_dict(obj)
这篇关于Python如何地柜解析这种数据类型,data__key__hello = "world"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文