python - 如何从作为字典列表中特定键的值的列表中删除空字符串?

标签 python

鉴于我是 Python 新手,而且我的背景是社会科学,我将尽力解释这个问题,提前感谢您提供的宝贵帮助!

我有一个存储在线食谱信息的字典列表。对于特定的键['ingredients'],我有一个字符串列表作为值。我想通过删除空字符串来清理列表。

以下是我的数据的示例:

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

我希望获得的关键“成分”的结果是:

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

我尝试过不同的代码:

<小时/>
for dct in data:
    for lst in dct['ingredients']:
        for element in lst:
            if element == '':
                dct['ingredients'] = lst.remove(element)
<小时/>
for dct in current_dict:
    for lst in dct['ingredients']:
        dct['ingredients'] = list(filter(lambda x: x!=''))
<小时/>
for dct in data:
    for lst in dct['ingredients']:
        for x in lst:
            if x == "":
                dct['ingredients'] = lst.remove(x)
<小时/>

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

最佳答案

使用 filter 的最快方法:

for dct in data:
    dct['ingredients'] = list(filter(None, dct['ingredients']))

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

相关文章:

python - Python 3.4+ 中的多个顺序抽象基类

python - 从 python 调用 c 程序时将数组传递给子进程模块的问题

python - 对于 string_list : s = func(s) can't change string s 中的 s

python - devpi::AttributeError: 'FileUpload' 对象没有属性 'value'::上传时

python - 如何使用 OpenCV 在 Plone 站点中显示网络摄像头捕获?

python - Django - 如何批量删除

python - Pandas 数据帧 : Sum of column values where values are list

Python:如何知道两个字典是否具有相同的键

python - 与我的 MYSQL connect_timeout 单位混淆

python - 如何重载类成员的分配?