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

แทรกข้อมูลที่จุดเริ่มต้นของ OrderedDict ใน Python


เมื่อต้องการเพิ่มคีย์-ค่าใหม่ที่จุดเริ่มต้นของ OrderedDict ใช้ update() แล้วตามด้วย move_to_end(key, last=False)

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

from collections import OrderedDict

od = OrderedDict([('Will', '1'), ('James', '2'), ('Rob', '4')])
print("The dictionary is:")
print(od)

od.update({'Mark': '7'})
od.move_to_end('Mark', last=False)

print("The resultant dictionary is:")
print(od)

ผลลัพธ์

The dictionary is: OrderedDict([('Will', '1'), ('James', '2'), ('Rob', '4')])
The resultant dictionary is: OrderedDict([('Mark', '7'), ('Will', '1'), ('James', '2'), ('Rob', '4')])

คำอธิบาย

  • สร้าง OrderedDict เริ่มต้นด้วยลิสต์ทัพเพิล

  • update({'Mark': '7'}) เพิ่มคีย์ใหม่ไว้ท้ายสุด (พฤติกรรมปกติ)

  • move_to_end('Mark', last=False) ย้ายคีย์ 'Mark' ไปจุดเริ่มต้น (last=False)

  • ผลลัพธ์: Mark อยู่หน้าสุด ตามด้วย Will, James, Rob