Python 程序 – 如果不存在特定值,则从字典列表中删除字典

pythonserver side programmingprogramming更新于 2025/10/22 13:32:17

当需要从字典列表中删除字典(如果字典中不存在特定值)时,可以使用简单迭代、‘del’ 运算符和 ‘break’ 语句。

示例

下面是相同的演示 −

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("结果列表是:")
print(my_list)

输出

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'}]
结果列表为:
[{'code': 1, 'fun': 'learn'}, {'code': 2, 'fun': 'code'}, {'code': 4, 'fun': 'teach'}, {'code': 4, 'fun': 'make'},
{'code': 4, 'fun': 'object'}]

解释

  • 定义一个字符串列表,并显示在控制台。

  • 列表被迭代,并且特定索引被检查为等于整数。

  • 这被分配给结果。

  • 这在控制台上显示为输出。


相关文章


有用资源