Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Replace value by Kth index value in Dictionary List
Sometimes you need to replace list values in dictionaries with specific elements from those lists. This technique uses isinstance() to identify list values and replaces them with the element at the Kth index.
Example
Below is a demonstration of replacing list values with their Kth index elements −
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, 'for': 10, 'fun': 9}, {'cool': 3, 'python': [7, 3, 9, 1]}]
The value of K is
2
The result is :
[{'python': 9, 'is': 8, 'good': 10}, {'python': 1, 'for': 10, 'fun': 9}, {'python': 9, 'cool': 3}]
How It Works
The algorithm follows these steps −
A list of dictionaries is defined with mixed value types (lists and integers)
The K value (index position) is set to 2
The target key ('python') is specified
The code iterates through each dictionary in the list
For each dictionary,
isinstance()checks if the value at the target key is a listIf it's a list, the entire list is replaced with the element at index K
Non-list values remain unchanged
Alternative Approach with Error Handling
Here's a safer version that handles potential index errors −
my_list = [{'python': [5, 7, 9, 1], 'is': 8, 'good': 10},
{'python': 1, 'for': 10, 'fun': 9},
{'cool': 3, 'python': [7, 3, 9, 1]}]
K = 2
my_key = "python"
for dictionary in my_list:
if my_key in dictionary and isinstance(dictionary[my_key], list):
try:
dictionary[my_key] = dictionary[my_key][K]
except IndexError:
print(f"Index {K} is out of range for list in dictionary")
print("The result is :")
print(my_list)
The result is :
[{'python': 9, 'is': 8, 'good': 10}, {'python': 1, 'for': 10, 'fun': 9}, {'python': 9, 'cool': 3}]
Conclusion
Use isinstance() to identify list values in dictionaries and replace them with specific indexed elements. Always consider adding error handling for safer code when dealing with variable-length lists.
