使用嵌套数组打印嵌套 OrderedDict 中键和值的所有路径

Print all paths to the keys and values in a nested OrderedDict with nested arrays

我正在尝试从具有数组和 OderedDicts 的嵌套数据结构中获取路径。问题是我在这里找到的函数:Find a given key's value in a nested ordered dict python 不适用于其中的数组。

我一直在 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', '.95'),
                                              ('description',
                                               'Two of our famous Belgian Waffles '
                                               'with plenty of real maple syrup'),
                                              ('calories', '650')]),
                                 OrderedDict([('name',
                                           'Strawberry Belgian Waffles'),
                                              ('price', '.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'] = .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))

如果您这样做是为了生成可以重新创建列表的代码,请考虑查看 json formatting