将数据字典输出树形结构
时间: 2023-10-28 15:06:14 浏览: 108
可以使用递归函数实现将数据字典输出为树形结构。以下是一个简单的示例代码:
```python
def print_tree(data, level=0):
for key, value in data.items():
print(" " * level + str(key))
if isinstance(value, dict):
print_tree(value, level+1)
else:
print(" " * (level+1) + str(value))
```
这个函数接受一个数据字典和一个可选的级别参数。它首先输出当前级别的键,然后检查该键对应的值是否也是一个字典。如果是,它递归地调用自身,将该值作为新的数据字典和级别+1作为新的级别传递。如果不是,它只是输出值。
你可以将你的数据字典传递给这个函数,例如:
```python
data = {
"animals": {
"mammals": {
"dogs": ["Beagle", "Boxer", "Dalmatian"],
"cats": ["Siamese", "Persian"]
},
"birds": {
"parrots": ["African Grey", "Amazon", "Cockatoo"],
"canaries": ["Red Factor", "Spanish Timbrado"]
}
},
"plants": {
"flowers": {
"roses": ["Climbing", "Floribunda", "Hybrid Tea"],
"tulips": ["French", "Parrot", "Rembrandt"]
},
"trees": {
"deciduous": ["Maple", "Oak", "Birch"],
"evergreen": ["Pine", "Spruce", "Fir"]
}
}
}
print_tree(data)
```
输出结果将是:
```
animals
mammals
dogs
Beagle
Boxer
Dalmatian
cats
Siamese
Persian
birds
parrots
African Grey
Amazon
Cockatoo
canaries
Red Factor
Spanish Timbrado
plants
flowers
roses
Climbing
Floribunda
Hybrid Tea
tulips
French
Parrot
Rembrandt
trees
deciduous
Maple
Oak
Birch
evergreen
Pine
Spruce
Fir
```
阅读全文