IUnknown
IUnknown

Reputation: 9809

Concatenate lists together

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.

Upvotes: 0

Views: 155

Answers (4)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

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']

Upvotes: 3

HennyH
HennyH

Reputation: 7944

>>> 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']

Upvotes: 0

Jared
Jared

Reputation: 26397

>>> d1 = {'A': [], 'C': ['SUV'], 'B': []}
>>> [ele for lst in d1.itervalues() for ele in lst]
['SUV']

Upvotes: 3

Jon Clements
Jon Clements

Reputation: 142106

from itertools import chain
d1={'A': [], 'C': ['SUV'], 'B': []}
print list(chain.from_iterable(d1.itervalues()))

Upvotes: 6

Related Questions