Home > Mobile >  Removing null entries from a list of dictionaries
Removing null entries from a list of dictionaries

Time:04-19

I have a list of dictionaries like this:

[
    {'property_a': 'a1', 'property_b': 'b1'},
    {'property_a': 'a2', 'property_b': 'b2'},
    {'property_a': 'a3'}
]

How can I remove the entries that do not have the property property_b? I have tried accessing the property name somehow (example below):

for entry in mylist['property_b']:
    for k in list(entry.keys()):
        if entry[k] == None:
            del entry[k]

But it doesn't work like that.

What I need is to remove those entries altogether, resulting in this list for example:

[
    {'property_a': 'a1', 'property_b': 'b1'},
    {'property_a': 'a2', 'property_b': 'b2'}
]

CodePudding user response:

Try:

lst = [
    {"property_a": "a1", "property_b": "b1"},
    {"property_a": "a2", "property_b": "b2"},
    {"property_a": "a3"},
]

lst = [d for d in lst if "property_b" in d]
print(lst)

Prints:

[
    {"property_a": "a1", "property_b": "b1"},
    {"property_a": "a2", "property_b": "b2"},
]

CodePudding user response:

mylist['property_b'] won't return anything as lists indices must always be integers (a list is just an array of items and 'property_b' is nested in those items so is not immediately accessible)

What you need to do is iterate through your list and check whether each dictionary contains 'property_b' as a key.

This may be done either of the two following ways:

new_list = []

for item in mylist:
  if 'property_b' in item:
   new_list.append(item)

This would be my preferred way (using list comprehension):

new_list = [item for item in mylist if 'property_b' in item]

They both do the same thing, the latter is just more elegant.

  • Related