【问题标题】:Print all paths to the keys and values in a nested OrderedDict with nested arrays使用嵌套数组打印嵌套 OrderedDict 中键和值的所有路径
【发布时间】:2019-10-05 19:42:48
【问题描述】:

我正在尝试从带有数组和 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', '$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

请原谅我的英语,我不是以英语为母语的人。

【问题讨论】:

    标签: python dictionary path nested ordereddictionary


    【解决方案1】:

    试试这个功能:

    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

    【讨论】:

    • 谢谢分配,我已经找了两个星期了,谢谢!
    猜你喜欢
    • 2016-04-22
    • 2016-01-21
    • 2020-08-25
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    相关资源
    最近更新 更多