Python 如果字典不包含特定键,如何从字典中删除字典
如何删除不包含特定键的词典。 例如,如下所示:Python 如果字典不包含特定键,如何从字典中删除字典,python,list,dictionary,Python,List,Dictionary,如何删除不包含特定键的词典。 例如,如下所示: myList = [ { "name" : "value", "price" : "value", "details" : "value", "status" : "value" }, {
myList = [
{
"name" : "value",
"price" : "value",
"details" : "value",
"status" : "value"
},
{
"name" : "value",
"price" : "value",
"details" : "value",
"status" : "value"
},
{
"name" : "value",
"price" : "value",
"details" : "value",
}
]
在给定的示例中,第三个字典不包含状态键,如何删除整个字典?您可以使用列表理解遍历每个dict,然后验证是否存在特定键,如下所示:
myList = [
{
"name" : "value",
"price" : "value",
"details" : "value",
"status" : "value"
},
{
"name" : "value",
"price" : "value",
"details" : "value",
"status" : "value"
},
{
"name" : "value",
"price" : "value",
"details" : "value",
}
]
print([ dic for dic in myList if dic.get('status', False)])
get方法如果退出,则返回键的值,否则返回False
结果将是:
[{'name': 'value', 'price': 'value', 'details': 'value', 'status': 'value'}, {'name': 'value', 'price': 'value', 'details': 'value', 'status': 'value'}]
希望这能对您有所帮助:您可以使用列表理解根据条件进行筛选
newList = [ item for item in myList if item.get("status") is not None]
最简单的方法是检查列表中的字典中是否存在键:
[x for x in myList if 'status' in x]
dic.获取“状态”,False可替换为dic.获取“状态”