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

PythonServer Side ProgrammingProgramming

When it is required to remove a dictionary from a list of dictionaries when a specific value is not present in it, a simple iteration, the ‘del’ operator and the ‘break’ statements are used.

Example

Below is a demonstration of the same −

my_list = [{"code" : 1, "fun" : "learn"},
   {"code" : 2, "fun" : "code"},
   {"code" : 3, "fun" : "test"},
   {"code" : 4, "fun" : "teach"},
   {"code" : 4, "fun" : "make"},
   {"code" : 4, "fun" : "object"}]

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

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

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

Output

The list of dictionary is :
[{'code': 1, 'fun': 'learn'}, {'code': 2, 'fun': 'code'}, {'code': 3, 'fun': 'test'}, {'code': 4, 'fun': 'teach'},
{'code': 4, 'fun': 'make'}, {'code': 4, 'fun': 'object'}]
The resultant list is :
[{'code': 1, 'fun': 'learn'}, {'code': 2, 'fun': 'code'}, {'code': 4, 'fun': 'teach'}, {'code': 4, 'fun': 'make'},
{'code': 4, 'fun': 'object'}]

Explanation

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

  • The list is iterated over, and the specific index is checked to be equal to an integer.

  • This is assigned to a result.

  • This is displayed as output on the console.

raja
Published on 13-Sep-2021 08:03:19
Advertisements