Simon
Simon

Reputation: 85

Eliminate empty values in python dict made of lists and arrays

I want to eliminate all empty value from a dict whose values are a mix of lists and nd array. So I tried with:

    res = [ele for ele in ({key: val for key, val in sub.items() if val} for sub in test_list) if ele]

but I get the error

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). And if I try:

AttributeError: 'list' object has no attribute 'any' 

I get the error

AttributeError: 'list' object has no attribute 'any'

So I am wondering if there is a more general way to delete empty values in python dict.

Upvotes: 1

Views: 136

Answers (3)

Red
Red

Reputation: 27547

@Jacob's answer works fine, though it is really inefficient.

Instead, you can take advantage of the built-in filter() method to filter out the empty dictionaries, and use the dict() method instead of using a dict comprehension:

res = filter(None, (dict(i for i in sub.items() if len(i[1])) for sub in test_list))

Upvotes: 0

soundstripe
soundstripe

Reputation: 1474

I think you've made this one more step complicated than necessary (as well as not including a complete example!)

The following example creates a new dict res with all values of test_dict that have non-empty values. I used len() here because that works on both lists and nd-arrays. For just lists, I'd omit the call to len() and just use val.

test_dict = {1: [], 2: [1,2,3], 3: [4,5,6]}
res = {key: val for key, val in test_list.items() if len(val)}

If you are wanting to use any(), you'd be finding dict values that are lists that contain at least one truthy item:

test_dict = {1: [], 2: [1,2,3], 3: [4,5,6]}
res = {key: val for key, val in test_list.items() if any(val)}

Upvotes: 1

Jacob Faib
Jacob Faib

Reputation: 1130

A common way to check empty for empty lists is to check len(list). So assuming your dict() looks like so

myDict = {
  1: [1,2,3],
  2: [],
  3: np.array([[1,2],[3,4],[5,6]])
}

Your list comprehension might look like

res = {k:v for k,v in myDict.items() if len(v)}

Note the len(v) in the dict comprehension

Upvotes: 1

Related Questions