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

การ Iterate Nested Dictionary แบบ Recursive ใน Python

Nested Dictionary ที่มีความลึกไม่คงที่ ต้องใช้ Recursive Function เพื่อเดินทาง (traverse) ทุกชั้น

ตัวอย่างข้อมูล

>> D1 = {
...     1: {2: {3: 4, 5: 6}, 3: {4: 5, 6: 7}},
...     2: {3: {4: 5}, 4: {6: 7}}
... }

Recursive Function

>> def iterdict(d):
...     for k, v in d.items():
...         if isinstance(v, dict):
...             iterdict(v)        # recursive call
...         else:
...             print(k, ":", v)

>>> iterdict(D1)

ผลลัพธ์

3 : 4
5 : 6
4 : 5
6 : 7
4 : 5
6 : 7

เวอร์ชันที่คืนค่า Generator (ยืดหยุ่นกว่า)

>> def iter_nested(d):
...     for k, v in d.items():
...         if isinstance(v, dict):
...             yield from iter_nested(v)
...         else:
...             yield (k, v)

>>> list(iter_nested(D1))
[(3, 4), (5, 6), (4, 5), (6, 7), (4, 5), (6, 7)]

การประยุกต์: หาค่าสูงสุด/ต่ำสุดใน Nested Dict

>> max(iter_nested(D1), key=lambda x: x[1])
(6, 7)

>>> min(iter_nested(D1), key=lambda x: x[1])
(3, 4)