Python – Replace value by Kth index value in Dictionary List

PythonServer Side ProgrammingProgramming

When it is required to replace the value by Kth index value in a list of dictionary, the ‘isinstance’ method and a simple iteration are used.

Example

Below is a demonstration of the same

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)

Output

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

Explanation

  • A list of dictionary is defined and is displayed on the console.

  • The value if K is defined and is displayed on the console.

  • The key element is defined.

  • The list is iterated over and the ‘isinstance’ method is used to check if a specific element is same type as that of list type.

  • If yes, the K value is placed instead of the specific element.

  • This is the output that is displayed on the console.

raja
Published on 20-Sep-2021 08:57:29
Advertisements