0

I have a dictionary where the value elements are lists:

d1={'A': [], 'C': ['SUV'], 'B': []} 

I need to concatenate the values into a single list ,only if the list is non-empty.
Expected output:

o=['SUV'] 

Help is appreciated.

0

4 Answers 4

6
from itertools import chain d1={'A': [], 'C': ['SUV'], 'B': []} print list(chain.from_iterable(d1.itervalues())) 
Sign up to request clarification or add additional context in comments.

1 Comment

This answer is better than Ashwin's because it fully utilizes the fact that chain can deal with iterators and not just eagerly generated sequences.
3
>>> d1 = {'A': [], 'C': ['SUV'], 'B': []} >>> [ele for lst in d1.itervalues() for ele in lst] ['SUV'] 

1 Comment

+1; I like this solution though I would replace values by itervalues.
3

You can use itertools.chain, but the order can be arbitrary as dicts are unordered collection. So may have have to sort the dict based on keys or values to get the desired result.

>>> d1={'A': [], 'C': ['SUV'], 'B': []} >>> from itertools import chain >>> list(chain(*d1.values())) # or use d1.itervalues() as it returns an iterator(memory efficient) ['SUV'] 

1 Comment

Please use chain.from_iterable for these jobs
0
>>> from operator import add >>> d1={'A': [], 'C': ['SUV'], 'B': []} >>> reduce(add,d1.itervalues()) ['SUV'] 

Or more comprehensive example:

>>> d2={'A': ["I","Don't","Drive"], 'C': ['SUV'], 'B': ["Boy"]} >>> reduce(add,d2.itervalues()) ['I', "Don't", 'Drive', 'SUV', 'Boy'] 

5 Comments

unfortunately this has O(N^2) behavior since you are creating a new list on each add
@jamylak True, this is a horribly inefficient approach (just had to put a functional approach out there)
what about sum(d2.itervalues(), [])
f = [], map(f.extend,d2.itervalues()) is also another poor method of solving it
@HennyH the other approaches are still functional, but I see what you mean

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.