遍历一个可能包含更多列表和字典的Python字典列表的迭代方式可以使用递归方法。以下是一个示例代码:
def iterate_dict_list(data):
for item in data:
if isinstance(item, list):
# 如果item是列表,则递归调用iterate_dict_list函数
iterate_dict_list(item)
elif isinstance(item, dict):
# 如果item是字典,则遍历字典的键值对
for key, value in item.items():
if isinstance(value, (list, dict)):
# 如果value是列表或字典,则递归调用iterate_dict_list函数
iterate_dict_list([value])
else:
# 处理其他类型的值
print(f"Key: {key}, Value: {value}")
# 示例数据
data = [
{"name": "John", "age": 30, "hobbies": ["reading", "coding"]},
{"name": "Jane", "age": 25, "hobbies": ["painting", "dancing"]},
{"name": "Bob", "age": 35, "hobbies": ["swimming", "hiking"], "address": {"street": "123 Main St", "city": "New York"}}
]
# 遍历字典列表
iterate_dict_list(data)
运行以上代码,会输出:
Key: name, Value: John
Key: age, Value: 30
Key: hobbies, Value: reading
Key: hobbies, Value: coding
Key: name, Value: Jane
Key: age, Value: 25
Key: hobbies, Value: painting
Key: hobbies, Value: dancing
Key: name, Value: Bob
Key: age, Value: 35
Key: hobbies, Value: swimming
Key: hobbies, Value: hiking
Key: street, Value: 123 Main St
Key: city, Value: New York
这样就可以遍历一个可能包含更多列表和字典的Python字典列表。