python - 如何从特定字典键的值列表中删除单词?

标签 python dictionary

我需要从字典列表中特定键的值中删除单词列表。

以下是我的数据的示例:

words = ['cloves', 'packed']

data = [{'title': 'Simple Enchiladas Verdes',
         'prep_time': '15 min',
         'cook_time': '30 min',
         'ingredients': ['chicken breast', 'tomato sauce', 'garlic cloves', 'fresh packed cilantro']
         'instructions': ['some text...'],
         'category': 'dessert',
         'cuisine': 'thai', 
         'article': ['some text...']
        },
        {...}, {...}]

期望的输出:

data = [{'title': 'Simple Enchiladas Verdes',
         'prep_time': '15 min',
         'cook_time': '30 min',
         'ingredients': ['chicken breast', 'tomato sauce', 'garlic', 'fresh cilantro']
        },
        {...}, {...}]

我尝试过不同的代码:

remove = '|'.join(words)
regex = re.compile(r'\b('+remove+r')\b', flags=re.IGNORECASE)

for dct in data:
    dct['ingredients']= list(filter(lambda x: regex.sub('', x), dct['ingredients']))

但这会返回以下错误:TypeError: sub() 缺少 1 个必需的位置参数:'string'

我尝试过的其他代码:

for dct in data:
    dct['ingredients']= list(filter(lambda x: x != words, dct['ingredients']))
for dct in data:
    dct['ingredients']=[[el for el in string if el in words ] for string in dct['ingredients']]
for dct in data:
    for string in dct['ingredients']:
        dct['ingredients'] = list(filter(lambda x: x not in words, dct['ingredients']))

但他们都没有解决我的问题。

最佳答案

为什么不使用 list 理解与 dictionary 理解:

data = [{k:([' '.join([s for s in x.split() if s not in words]) for x in v] if k == 'ingredients' else v) for k, v in i.items()} for i in data]

关于python - 如何从特定字典键的值列表中删除单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56252703/

相关文章:

dictionary - 项目列表的 Golang 类型断言

python - Pandas 数据框 - 基于组的每列的总和

python - 如何在python中执行直方图均衡

python - 为什么在该可哈希对象的集合中找不到我的可哈希对象,该集合是另一个对象的属性?

python - 从字典中理解选择器

python - 字典到python中的字典

python - Jinja 使用 for 列出嵌套 JSON

python - 这个 for 循环代码(带有 `if not in` 条件)可以转换为列表理解吗?

python - 如何使用python从 "../../"和另一个路径获取正确的文件路径

python - LPTHW 练习 43 - 通过从字典返回构造函数来创建对象