Python 以嵌套顺序打印键和值的所有路径使用嵌套数组

Python 以嵌套顺序打印键和值的所有路径使用嵌套数组,python,dictionary,path,nested,ordereddictionary,Python,Dictionary,Path,Nested,Ordereddictionary,我试图从带有数组和OderedDicts的嵌套数据结构中获取路径。问题是我在这里找到的函数:不能与其中的数组一起工作 我一直在windows环境下用Python版本3.7.3尝试这一点 这是我希望的方式,但对于阵列: from collections import OrderedDict mydict = OrderedDict ( {'a': OrderedDict ( {'b': OrderedDict ( [ ('chart_lay

我试图从带有数组和OderedDicts的嵌套数据结构中获取路径。问题是我在这里找到的函数:不能与其中的数组一起工作

我一直在windows环境下用Python版本3.7.3尝试这一点

这是我希望的方式,但对于阵列:

from collections import OrderedDict

mydict = OrderedDict ( {'a':
            OrderedDict ( {'b':
                OrderedDict ( [ ('chart_layout', '3'),
                 ('client_name', 'Sport Parents (Regrouped)'),
                 ('sort_order', 'asending'),
                 ('chart_type', 'pie'),
                 ('powerpoint_color', 'blue'),
                 ('crossbreak', 'Total')
                 ] ) } ) } )

def listRecursive (d, path = None):
    if not path: path = []
    for k, v in d.items ():
        if isinstance (v, OrderedDict):
            for path, found in listRecursive (v, path + [k] ):
                yield path, found
        if isinstance (v, str):
            yield path + [k], v

for path, found in listRecursive (mydict):
    print (path, found)
输出:

['a', 'b', 'chart_layout'] 3
['a', 'b', 'client_name'] Sport Parents (Regrouped)
['a', 'b', 'sort_order'] asending
['a', 'b', 'chart_type'] pie
['a', 'b', 'powerpoint_color'] blue
['a', 'b', 'crossbreak'] Total
此集合不是实际集合。它更多地嵌套在数组中


xml_order_dict = OrderedDict([('breakfast_menu',
                               OrderedDict([('food',
                                [OrderedDict([('name', 'Belgian Waffles'),
                                              ('price', '$5.95'),
                                              ('description',
                                               'Two of our famous Belgian Waffles '
                                               'with plenty of real maple syrup'),
                                              ('calories', '650')]),
                                 OrderedDict([('name',
                                           'Strawberry Belgian Waffles'),
                                              ('price', '$7.95'),
                                              ('description',
                                               'Light Belgian waffles covered with '
                                               'strawberries and whipped cream'),
                                              ('calories', '900')
                                             ])])]))])
def ListTags(d, key):
    for k, v in d.items ():
        if isinstance (v, OrderedDict):
            for found in listRecursive (v, key):
                yield found
        if k == key:
            yield v

for found in ListTags(xml_order_dict):
    print (found)
预期结果如下: 标记路径 标记的结果

输入:

for found in ListTags(xml_order_dict):
    print (found)
输出: 路径=结果

breakfast_menu['breakfast_menu']['food'][0]['name'] = Belgian Waffles
breakfast_menu['breakfast_menu']['food'][0]['price'] = $5.95
....
最后一个输出:

breakfast_menu['breakfast_menu']['food'][1]['calories'] = 900
请原谅,我不是以英语为母语的人。

试试这个功能:

def list_recursive(mydict, path=()):
    if type(mydict) is list:
        for i, item in enumerate(mydict):
            list_recursive(item, path=(*path, i))
        return
    for k, v in mydict.items():
        if type(v) is str:
            print(*map(
                lambda x:f"['{x}']" if type(x) is str else f"[{x}]",
                (*path, k)
            ), '=', v, sep='')
        else:
            list_recursive(v, path=(*path, k))

如果你这样做是为了生成可以重新创建列表的代码,考虑考虑一下。

谢谢分配,我已经找了两个星期了,谢谢!