Python 3.7.3下遍历含数组的嵌套OrderedDict键值路径
处理嵌套OrderedDict和数组的键值对路径遍历
嘿,我来帮你解决这个问题!你需要的是能同时遍历OrderedDict和列表(数组)的递归函数,还要输出指定格式的路径字符串。我修改了你的原函数,让它能完美处理包含数组的嵌套结构,同时调整了输出格式来匹配你的需求。
修改后的完整代码
from collections import OrderedDict def list_recursive(data, root_name, path=None): if path is None: path = [] if isinstance(data, OrderedDict): for k, v in data.items(): # 递归处理OrderedDict的子元素 yield from list_recursive(v, root_name, path + [('dict', k)]) elif isinstance(data, list): for i, item in enumerate(data): # 递归处理列表的子元素,记录索引 yield from list_recursive(item, root_name, path + [('list', i)]) else: # 处理叶子节点,生成指定格式的路径字符串 path_str = root_name for elem_type, elem_val in path: if elem_type == 'dict': path_str += f"['{elem_val}']" elif elem_type == 'list': path_str += f"[{elem_val}]" yield f"{path_str} = {data}" # 测试你的示例数据 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') ]) ]) ])) ]) # 遍历并打印结果 for line in list_recursive(xml_order_dict, 'breakfast_menu'): print(line)
代码说明
- 新增列表处理逻辑:函数现在会判断当前元素是否为
list类型,遍历列表时记录每个元素的索引,将索引作为路径的一部分传递下去。 - 路径类型标记:用
('dict', key)和('list', index)的元组来区分路径中的字典键和列表索引,方便后续生成格式正确的路径字符串。 - 输出格式定制:在叶子节点处,根据路径中的标记拼接出你需要的
root_name['key'][index]['key']格式的字符串,再和值拼接成最终输出。
测试输出
运行上述代码后,你会得到完全符合期望的输出:
breakfast_menu['breakfast_menu']['food'][0]['name'] = Belgian Waffles breakfast_menu['breakfast_menu']['food'][0]['price'] = $5.95 breakfast_menu['breakfast_menu']['food'][0]['description'] = Two of our famous Belgian Waffles with plenty of real maple syrup breakfast_menu['breakfast_menu']['food'][0]['calories'] = 650 breakfast_menu['breakfast_menu']['food'][1]['name'] = Strawberry Belgian Waffles breakfast_menu['breakfast_menu']['food'][1]['price'] = $7.95 breakfast_menu['breakfast_menu']['food'][1]['description'] = Light Belgian waffles covered with strawberries and whipped cream breakfast_menu['breakfast_menu']['food'][1]['calories'] = 900
内容的提问来源于stack exchange,提问作者esp0xdeadbeef
相关产品推荐
相关产品推荐

