Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果字典不包含特定键,如何从字典中删除字典_Python_List_Dictionary - Fatal编程技术网

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.获取“状态”