user430
user430

Reputation: 155

Write values of dictionary in list if non empty

I have the following dictionary:

dict = {
       'field1': ('foo','bar'), 
       'field2': ('spam',''),
       'field3': ['apples', 'oranges']
       }

and I'd like write the values in a list, but only if non-empty:

list = ['foo', 'bar', 'apples', 'oranges']

can I use dict.values() this? how do I check for the second element of the tuple to be non empty?

Upvotes: 1

Views: 175

Answers (3)

Austin
Austin

Reputation: 26047

Use a map with list-comprehension and then flat list to match desired output:

from itertools import chain

d = {
    'field1': ('foo','bar'),
    'field2': ('spam',''),
    'field3': ['apples', 'oranges']
    }

print(list(chain.from_iterable([v for v in d.values() if all(map(lambda x: any(x), v))])))

# ['foo', 'bar', 'apples', 'oranges']

Note: You shouldn't call you dictionary as dict since it shadows built-in dict.

Upvotes: -1

Ali Shahrivarian
Ali Shahrivarian

Reputation: 311

import itertools
dict_ = {
       'field1': ('foo','bar'), 
       'field2': ('spam',''),
       'field3': ['apples', 'oranges']
       }

list_ = list(itertools.chain(*(lists for lists in dict_.values() if all(lists))))

print(list_)
# ['foo', 'bar', 'apples', 'oranges']

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71471

You can use a list comprehension:

dic = {
   'field1': ('foo','bar'), 
   'field2': ('spam',''),
   'field3': ['apples', 'oranges']
   }
new_result = [i for b in dic.values() for i in b if all(b)]

Output:

['foo', 'bar', 'apples', 'oranges']

Upvotes: 2

Related Questions