以点表示法返回python嵌套dict / json文档中所有变量名的列表 [英] Return a list of all variable names in a python nested dict/json document in dot notation

查看:197
本文介绍了以点表示法返回python嵌套dict / json文档中所有变量名的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个以JSON-esque格式任意嵌套的dict / array的python函数,并返回一个将其包含的所有变量名称的字符串列表,到无限深度。所以,如果对象是...

  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屋!

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