python 嵌套字典遍历_python中遍历字典的方法

python 嵌套字典遍历_python中遍历字典的方法在 Python 中 遍历列表中嵌套的字典可以通过以下几种方法实现 递归方法 pythondef traverse nested dict d depth 0 for key value in d items print depth str key if isinstance value dict traverse nested dict value

在Python中,遍历列表中嵌套的字典可以通过以下几种方法实现:

递归方法

 def traverse_nested_dict(d, depth=0): for key, value in d.items(): print(' ' * depth + str(key)) if isinstance(value, dict): traverse_nested_dict(value, depth + 2) else: print(' ' * (depth + 2) + str(value)) 

循环方法

 def print_nested_dict(d, indent=0): for key, value in d.items(): print(' ' * indent + str(key)) if isinstance(value, dict): print_nested_dict(value, indent + 2) else: print(' ' * (indent + 2) + str(value)) 

使用栈的迭代方法

 def traverse_dict(d): stack = [(d, '')] while stack: cur, prefix = stack.pop() for key, value in cur.items(): if isinstance(value, dict): stack.append((value, prefix + key + '/')) else: print(prefix + key + ':', value) 

遍历列表中的字典

 my_list = [ {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 35} ] for item in my_list: for key, value in item.items(): print(key, value) 

或者使用索引和循环:

 for i in range(len(my_list)): for key, value in my_list[i].items(): print(key, value) 

以上方法都可以遍历列表中嵌套的字典,并打印出字典的键和值。你可以根据具体需求选择合适的方法

编程小号
上一篇 2025-03-12 10:36
下一篇 2025-03-12 10:28

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/114870.html