Python – 用字典列表中的第 K 個索引值替換值


當需要用字典列表的第 K 個索引值替換值時,會用到 ‘isinstance’ 方法和一個簡單的迭代。

示例

下面是透過演示實現的

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}]

說明

  • 定義了一個字典列表並顯示在控制檯上。

  • 如果 K 存在,則顯示在控制檯上。

  • 定義關鍵元素。

  • 遍歷列表,使用 ‘isinstance’ 方法檢查特定元素是否與列表型別相同。

  • 如果是,則將 K 值放置在特定元素之中。

  • 這是控制檯上顯示的輸出。

更新時間:20-9-2021

已瀏覽 526 次

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.