在Python中,可以使用递归函数来遍历一个对象,获取键和所有父键。
下面是一个示例代码:
def get_keys(obj, parent_keys=[]):
# 遍历字典类型的对象
if isinstance(obj, dict):
for key, value in obj.items():
# 将当前键添加到父键列表中
current_keys = parent_keys + [key]
print("Key:", key)
print("Parent Keys:", current_keys)
# 递归调用,传入当前值和当前键列表
get_keys(value, current_keys)
# 遍历列表类型的对象
elif isinstance(obj, list):
for index, value in enumerate(obj):
# 将当前索引添加到父键列表中
current_keys = parent_keys + [index]
print("Index:", index)
print("Parent Keys:", current_keys)
# 递归调用,传入当前值和当前键列表
get_keys(value, current_keys)
# 遍历其他类型的对象,例如字符串、数字等
else:
print("Value:", obj)
print("Parent Keys:", parent_keys)
# 示例数据
data = {
"name": "Alice",
"age": 25,
"address": {
"street": "123 Main St",
"city": "New York"
},
"hobbies": ["reading", "painting"]
}
# 调用函数进行遍历
get_keys(data)
输出结果:
Key: name
Parent Keys: ['name']
Value: Alice
Parent Keys: ['name']
Key: age
Parent Keys: ['age']
Value: 25
Parent Keys: ['age']
Key: address
Parent Keys: ['address']
Key: street
Parent Keys: ['address', 'street']
Value: 123 Main St
Parent Keys: ['address', 'street']
Key: city
Parent Keys: ['address', 'city']
Value: New York
Parent Keys: ['address', 'city']
Key: hobbies
Parent Keys: ['hobbies']
Index: 0
Parent Keys: ['hobbies', 0]
Value: reading
Parent Keys: ['hobbies', 0]
Index: 1
Parent Keys: ['hobbies', 1]
Value: painting
Parent Keys: ['hobbies', 1]