annag
annag

Reputation: 25

How can I remove empty strings from a list that is a value of a specific key in a list of dictionaries?

Given that I'm new in Python and my background is in social sciences I I'll try to do my best to explain the problem and I thank you in advance for the valuable help!

I have a list of dictionaries storing information of online recipes. For the specific key ['ingredients'], I have a list of strings as value. I would like to clean the list by deleting the empty strings.

Here is an example of how my data looks like:

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

The result that I would like to obtain for the key 'ingredients' is:

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

I have tried different codes:


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)

But none of them solve my problem.

Upvotes: 1

Views: 69

Answers (4)

Ali BENALI
Ali BENALI

Reputation: 745

try this

def removeEmtyItems(liste, copyliste):
for item  in copyliste:
    if item=="":
        liste.remove(item)

return liste


for dict in data:
    for value in dict.values():
        if isinstance(value, list):
            copyliste=list(value)
            removeEmtyItems(value, copyliste)

print(data)

or just

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

Upvotes: 0

sentence
sentence

Reputation: 8933

The fastest way using filter:

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

Upvotes: 1

Valentino
Valentino

Reputation: 7361

You can use a list comprehension:

for dct in data:
    dct['ingredients'] = [el for el in dct['ingredients'] if el != '']

Upvotes: 0

javidcf
javidcf

Reputation: 59731

You are quite close. You just need to do:

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

What happens here is, for every dictionary dct in data, you take dct['ingredients'] and pass it to through the filter function, with the predicate lambda x: x != ''. The result is an "iterable", something from where you can get one element at a time. You then use list on that to obtain a proper list, and assign the result back to dct['ingredients'] to replace the original list.

Upvotes: 0

Related Questions