【发布时间】: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