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.
from itertools import chain d1={'A': [], 'C': ['SUV'], 'B': []} print list(chain.from_iterable(d1.itervalues())) >>> d1 = {'A': [], 'C': ['SUV'], 'B': []} >>> [ele for lst in d1.itervalues() for ele in lst] ['SUV'] values by itervalues.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'] chain.from_iterable for these jobs>>> 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'] addsum(d2.itervalues(), [])f = [], map(f.extend,d2.itervalues()) is also another poor method of solving it