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

เพิ่ม Key และ Value ของ Dictionary ตามลำดับใน Python


ภาพรวม

เมื่อต้องการเพิ่ม Key และ Value ของ Dictionary ตามลำดับ สามารถใช้เมธอด list() ร่วมกับเมธอด .keys() และ .values() เพื่อเข้าถึง Key และ Value เฉพาะ

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

my_dict = {"January": 1, "Feb": 2, "March": 3, 'April':4, 'May': 5, 'June':6}
print("The dictionary is : ")
print(my_dict)
my_result = list(my_dict.keys()) + list(my_dict.values())
print("The ordered key and value are : ")
print(my_result)

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

The dictionary is : {'January': 1, 'Feb': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6}
The ordered key and value are : ['January', 'Feb', 'March', 'April', 'May', 'June', 1, 2, 3, 4, 5, 6]

คำอธิบาย

  • นิยาม Dictionary และแสดงบนคอนโซล
  • เข้าถึง Key ของ Dictionary ด้วยเมธอด keys() และ Value ด้วย values()
  • แปลงเป็น List และต่อกันด้วยออปิเรเตอร์ +
  • แสดงผลลัพธ์บนคอนโซล