Python ตอนที่ 124 การคัดลอกข้อมูลประเภท Dictionary

ถ้าต้องการคัดลอกข้อมูลประเภท Dictionary สามารถทำได้โดยใช้เมธอด copy()

phone = {
    "brand": "Apple",
    "model": "iPhone 14",
    "year": 2022
}
myDict = phone.copy()
print(myDict)
  • บรรทัดที่ 6 ใช้เมธอด copy() คัดลอก Dictionary โดยคัดลอกจากตัวแปร phone แล้วนำมาเก็บไว้ที่ตัวแปร myDict

ผลลัพธ์ ตัวแปร myDict มีข้อมูลเหมือนกันกับตัวแปร phone

{‘brand’: ‘Apple’, ‘model’: ‘iPhone 14’, ‘year’: 2022}

อีกวิธีหนึ่งในการคัดลอกข้อมูลประเภท Dictionary คือ ใช้เมธอด dict()

phone = {
    "brand": "Apple",
    "model": "iPhone 14",
    "year": 2022
}
myDict = dict(phone)
print(myDict)
  • บรรทัดที่ 6 สร้างตัวแปรชื่อว่า myDict ให้เป็นตัวแปรข้อมูลประเภท Dictionary พร้อมกำหนดค่า ด้วยเมธอด dict() โดยระบุอากิวเมนต์เป็นตัวแปร phone ซึ่งเป็นข้อมูลประเภท Dictionary

ผลลัพธ์ ตัวแปร myDict มีค่าเหมือนกันกับตัวแปร phone ทุกประการ

{‘brand’: ‘Apple’, ‘model’: ‘iPhone 14’, ‘year’: 2022}