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

Python - วิธีการกลับคีย์และค่าในดิกชันนารี (Invert Mapping)

ดิกชันนารีเป็นคอลเลกชันที่ไม่มีลำดับ เปลี่ยนแปลงได้ และมีดัชนี ใน Python เขียนดิกชันนารีด้วยวงเล็บปีกกา และมีคีย์และค่า ใช้กันอย่างกว้างขวางในการเขียนโปรแกรมประจำวัน พัฒนาเว็บ และ Machine Learning

ตัวอย่างโค้ด

1. ใช้ Dictionary Comprehension (แนะนำ)

# เริ่มต้นดิกชันนารี
ini_dict = {101: "vishesh", 201: "laptop"}
print("initial dictionary :", str(ini_dict))

# กลับ mapping ด้วย dict comprehension
inv_dict = {v: k for k, v in ini_dict.items()}

print("inverse mapped dictionary :", str(inv_dict))

2. ใช้ zip() และ dict()

ini_dict = {101: "vishesh", 201: "laptop"}
print("initial dictionary :", str(ini_dict))

# กลับ mapping ด้วย zip และ dict
inv_dict = dict(zip(ini_dict.values(), ini_dict.keys()))

print("inverse mapped dictionary :", str(inv_dict))

3. ใช้ map() และ reversed()

ini_dict = {101: "akshat", 201: "ball"}
print("initial dictionary :", str(ini_dict))

# กลับ mapping ด้วย map และ reversed
inv_dict = dict(map(reversed, ini_dict.items()))

print("inverse mapped dictionary :", str(inv_dict))

4. ใช้ Lambda (โค้ดตัวอย่างมีข้อผิดพลาด - ไม่ได้ assign ผลลัพธ์)

# โค้ดต้นฉบับมีปัญหา: lambda ไม่ได้ถูกเรียกใช้
# วิธีที่ถูกต้อง:
ini_dict = {101: "akshat", 201: "ball"}
print("initial dictionary :", str(ini_dict))

inv_dict = (lambda d: {v: k for k, v in d.items()})(ini_dict)
# หรือง่ายกว่า:
inv_dict = {v: k for k, v in ini_dict.items()}

print("inverse mapped dictionary :", str(inv_dict))

ผลลัพธ์ตัวอย่าง


initial dictionary : {201: 'laptop', 101: 'vishesh'}
inverse mapped dictionary : {'laptop': 201, 'vishesh': 101}

หมายเหตุสำคัญ

  • การกลับ mapping ต้องการให้ ค่า (values) เป็น unique มิฉะนั้นข้อมูลจะสูญหาย
  • Dictionary Comprehension เป็นวิธีที่อ่านง่ายและ Pythonic ที่สุด
  • ถ้าค่าซ้ำกัน ต้องตัดสินใจว่าจะเก็บคีย์ไหน (ตัวแรก/ตัวสุดท้าย/รวมเป็นลิสต์)