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

แปลง Nested Dictionary เป็น Flat Dictionary ใน Python


ปัญหา

แปลง Dictionary ซ้อนหลายชั้น (Nested) ให้เป็น Dictionary ชั้นเดียว (Flat) โดยรวมคีย์ด้วย separator

ตัวอย่าง

input = {
    "id": "0001",
    "name": "hotdog",
    "image": {
        "url": "images/0001.jpg",
        "thumbnail": {
            "url": "images/thumbnails/0001.jpg",
            "height,width": "2x4"
        }
    }
}

# Output:
{
    'id': '0001',
    'name': 'hotdog',
    'image_url': 'images/0001.jpg',
    'image_thumbnail_url': 'images/thumbnails/0001.jpg',
    'image_thumbnail_height,width': '2x4'
}

วิธีที่ 1: Recursive Function (ไม่ต้องติดตั้งเพิ่ม)

def flatten_dict(d, parent_key='', sep='_'):
    items = {}
    for k, v in d.items():
        new_key = f"{parent_key}{sep}{k}" if parent_key else k
        if isinstance(v, dict):
            items.update(flatten_dict(v, new_key, sep))
        else:
            items[new_key] = v
    return items

flat = flatten_dict(nested_dict)

วิธีที่ 2: ใช้ไลบรารี cherrypicker

pip install cherrypicker
from cherrypicker import CherryPicker
flat = CherryPicker(nested_dict).flatten().get()
# separator เริ่มต้นคือ '-'

การเลือกใช้

  • Recursive: ไม่ต้องพึ่งแพ็กเกจควบคุม separator เองได้
  • cherrypicker: สะดวก รองรับ JSON path query เพิ่มเติม