📜  Python - 用字典列表中的第 K 个索引值替换值

📅  最后修改于: 2022-05-13 01:55:44.526000             🧑  作者: Mango

Python - 用字典列表中的第 K 个索引值替换值

给定一个字典列表,任务是编写一个Python程序,如果键的值是列表,则用值的第 k 个索引替换特定键的值。

例子:

方法 #1:使用循环 + isinstance()

在这里,我们使用 isinstance() 来检查值的列表类型,并使用循环来遍历字典。

Python3
# Python3 code to demonstrate working of
# Replace value by Kth index value in Dictionary List
# Using loop + isinstance()
  
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
             {'gfg': 1, 'for': 10, 'geeks': 9},
             {'love': 3, 'gfg': [7, 3, 9, 1]}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 2
  
# initializing Key
key = "gfg"
  
for sub in test_list:
  
    # using isinstance() to check for list
    if isinstance(sub[key], list):
        sub[key] = sub[key][K]
  
# printing result
print("The Modified Dictionaries : " + str(test_list))


Python3
# Python3 code to demonstrate working of
# Replace value by Kth index value in Dictionary List
# Using dictionary comprehension + isinstance()
  
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
             {'gfg': 1, 'for': 10, 'geeks': 9},
             {'love': 3, 'gfg': [7, 3, 9, 1]}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 2
  
# initializing Key
key = "gfg"
  
# intermediate Dictionaries constructed using dictionary comprehension
res = [{newkey: (val[K] if isinstance(val, list) and newkey == key else val)
        for newkey, val in sub.items()} for sub in test_list]
  
# printing result
print("The Modified Dictionaries : " + str(res))


输出:

方法#2:使用字典理解+ isinstance()

在此,我们使用 isinstance() 使用修改后的字典值重建字典,并使用字典理解来形成中间字典。

蟒蛇3

# Python3 code to demonstrate working of
# Replace value by Kth index value in Dictionary List
# Using dictionary comprehension + isinstance()
  
# initializing list
test_list = [{'gfg': [5, 7, 9, 1], 'is': 8, 'good': 10},
             {'gfg': 1, 'for': 10, 'geeks': 9},
             {'love': 3, 'gfg': [7, 3, 9, 1]}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 2
  
# initializing Key
key = "gfg"
  
# intermediate Dictionaries constructed using dictionary comprehension
res = [{newkey: (val[K] if isinstance(val, list) and newkey == key else val)
        for newkey, val in sub.items()} for sub in test_list]
  
# printing result
print("The Modified Dictionaries : " + str(res))

输出: