以点表示法返回python嵌套dict / json文档中所有变量名的列表 [英] Return a list of all variable names in a python nested dict/json document in dot notation
本文介绍了以点表示法返回python嵌套dict / json文档中所有变量名的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
x = {
'a':'meow',
'b':{
'c':'asd'
},
'd':[
{
e:stuff
f:1
},
{
e:更多东西,
f:2
}
]
}
mylist = f(x) code>将返回...
>>> mylist
['a','b','b.c','d [0] .e','d [0] .f','d [1] .e','d [ 1] .f']
解决方案
def dot_notation(obj,prefix =''):
if isinstance(obj,dict):
if prefix:prefix + ='。'
for k,v in obj .items():
对于dot_notation中的res(v,前缀+ str(k)):
yield res
elif isinstance(obj,list):
for i,v in enumerate(obj):
for dot in dot_notation(v,prefix +'['+ str(i)+']'):
yield res
else:
yield prefix
示例:
code>>>> list(dot_notation(x))
['a','b.c','d [0] .e','d [0] .f','d [1] .e' d [1] .f']
I'm looking for a function that operates on a python arbitrarily nested dict/array in JSON-esque format and returns a list of strings keying all the variable names it contains, to infinite depth. So, if the object is...
x = {
'a': 'meow',
'b': {
'c': 'asd'
},
'd': [
{
"e": "stuff",
"f": 1
},
{
"e": "more stuff",
"f": 2
}
]
}
mylist = f(x)
would return...
>>> mylist
['a', 'b', 'b.c', 'd[0].e', 'd[0].f', 'd[1].e', 'd[1].f']
解决方案
def dot_notation(obj, prefix=''):
if isinstance(obj, dict):
if prefix: prefix += '.'
for k, v in obj.items():
for res in dot_notation(v, prefix+str(k)):
yield res
elif isinstance(obj, list):
for i, v in enumerate(obj):
for res in dot_notation(v, prefix+'['+str(i)+']'):
yield res
else:
yield prefix
Example:
>>> list(dot_notation(x))
['a', 'b.c', 'd[0].e', 'd[0].f', 'd[1].e', 'd[1].f']
这篇关于以点表示法返回python嵌套dict / json文档中所有变量名的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文