【问题标题】:How to check if at least a key exist in a dictionary based on a list of string? [closed]如何根据字符串列表检查字典中是否至少存在一个键? [关闭]
【发布时间】:2022-01-20 00:32:51
【问题描述】:

我有一个字符串列表:

fields = ["website", "product_url", "catalog_url", "dop_url", "nf_url"]

还有一个字典列表urls_list

我的目标是通过删除字典的所有键都不是列表fields 的字符串的字典来清理我的字典列表urls_list。 如果字典的至少一个键是"website""product_url""catalog_url""dop_url""nf_url",则字典应保留而不是删除。

我看到了很多关于 any() 或 all() 的例子,但我很难找到适合我特定需求的东西。

【问题讨论】:

标签: python list dictionary


【解决方案1】:

易于理解的解决方案:

fields = ["website", "product_url", "catalog_url", "dop_url", "nf_url"]
urls_list = [d for d in urls_list if any(k in d for k in fields)]

如果列表需要原地编辑,可以使用如下语法:

urls_list[:] = # etc.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 2020-08-30
    相关资源
    最近更新 更多