Dictionary Python có thể lồng nhau (dictionary trong dictionary). Bài viết tính độ sâu (depth) của dictionary lồng nhau.
Cách 1: Chuyển thành string đếm '{'
Chuyển dict thành string, đếm số ký tự {.
dictA = {1: 'Sun', 2: {3: {4: 'Mon'}}}
dictStr = str(dictA)
cnt = sum(1 for ch in dictStr if ch == '{')
print("Độ sâu dictionary:", cnt) # 3
Cách 2: Đệ quy (Recursion)
Hàm đệ quy kiểm tra giá trị có phải dict không, nếu có thì gọi lại và lấy max.
def finddepth(dictA):
if isinstance(dictA, dict):
return 1 + (max(map(finddepth, dictA.values())) if dictA else 0)
return 0
dictA = {1: 'Sun', 2: {3: {4: 'Mon'}}}
print("Độ sâu dictionary:", finddepth(dictA)) # 3