Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

หาความลึกของ Nested Dictionary ใน Python

คำนวณระดับการซ้อนของ Dictionary (Depth)

Dictionary อาจมี Dictionary ซ้อนอยู่ภายใน ต้องการหาความลึกสูงสุด (จำนวนชั้น)

วิธีที่ 1: นับ '{' ใน String Representation


d = {1:'Sun', 2:{3:{4:'Mon'}}}
depth = str(d).count('{')
print(depth)  # 3

วิธีที่ 2: ใช้ Recursion


def dict_depth(d):
    if not isinstance(d, dict) or not d:
        return 0
    return 1 + max(map(dict_depth, d.values()))

print(dict_depth({1:'Sun', 2:{3:{4:'Mon'}}}))  # 3