Python – Remove dictionary from a list of dictionaries if a particular value is not present

PythonServer Side ProgrammingProgramming

When it is required to remove dictionary from a list of dictionaries if a particular value is not present, a simple iteration and the ‘del’ operator is used.

Example

Below is a demonstration of the same −

my_list = [{"id" : 1, "data" : "Python"},
   {"id" : 2, "data" : "Code"},
   {"id" : 3, "data" : "Learn"}]

print("The list is :")
print(my_list)

for index in range(len(my_list)):
   if my_list[index]['id'] == 2:
      del my_list[index]
      break

print("The result is :")
print(my_list)

Output

The list is :
[{'id': 1, 'data': 'Python'}, {'id': 2, 'data': 'Code'}, {'id': 3, 'data': 'Learn'}]
The result is :
[{'id': 1, 'data': 'Python'}, {'id': 3, 'data': 'Learn'}]

Explanation

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

  • The list of dictionary is iterated over, and the ‘value’ associated with every key is checked to equivalent to 2.

  • If yes, that specific element is deleted.

  • The control breaks out of the loop.

  • In the end, this list of dictionary is displayed as output on the console.

raja
Published on 08-Sep-2021 06:43:38

Advertisements