
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python – Replace value by Kth index value in Dictionary List
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.
- Related Articles
- Python – Sort Dictionary List by Key’s ith Index value
- Python – Convert List to Index and Value dictionary
- Program to find largest kth index value of one list in Python
- Dictionary with index as value in Python
- Python – Index Value repetition in List
- Python - Clearing list as dictionary value
- Accessing index and value in a Python list
- Python program to Convert Matrix to Dictionary Value List
- How to sort a Python dictionary by value?
- Python – Extract Key’s Value, if Key Present in List and Dictionary
- Filter Tuples by Kth element from List in Python
- Accessing Key-value in a Python Dictionary
- Index minimum value Record in Python
- Python - Filter dictionaries by values in Kth Key in list
- Count number of items in a dictionary value that is a list in Python

Advertisements