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

Python - แทนที่ค่าใน Dictionary List ด้วยค่าที่ Index K

ในลิสต์ของ Dictionary ถ้า Value ของ Key ที่กำหนดเป็น List ให้แทนที่ Value นั้นด้วยสมาชิก Index K ของ List นั้น

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

my_list = [{'python': [5, 7, 9, 1], 'is': 8, 'good': 10},
           {'python': 1, 'for': 10, 'fun': 9},
           {'cool': 3, 'python': [7, 3, 9, 1]}]

print("The list is :")
print(my_list)

K = 2
print("The value of K is")
print(K)

my_key = "python"
for index in my_list:
    if isinstance(index[my_key], list):
        index[my_key] = index[my_key][K]

print("The result is :")
print(my_list)

ผลลัพธ์

The list is : [{'python': [5, 7, 9, 1], 'is': 8, 'good': 10}, {'python': 1, 'fun': 9, 'for': 10}, {'python': [7, 3, 9, 1], 'cool': 3}]
The value of K is 2
The result is : [{'python': 9, 'is': 8, 'good': 10}, {'python': 1, 'fun': 9, 'for': 10}, {'python': 9, 'cool': 3}]

คำอธิบาย

  • isinstance(index[my_key], list) เช็คว่า Value เป็น List หรือไม่
  • ถ้าเป็น List: แทนที่ด้วย index[my_key][K] (สมาชิก Index K)
  • ถ้าไม่ใช่ List (เช่น Dict ที่ 2: 'python': 1) -> ข้ามไป
  • แก้ไข In-place