One-liner to merge lists?

Frank Millman frank at chagford.com
Tue Feb 22 04:19:33 EST 2022


Hi all

I think this should be a simple one-liner, but I cannot figure it out.

I have a dictionary with a number of keys, where each value is a single 
list -

 >>> d = {1: ['aaa', 'bbb', 'ccc'], 2: ['fff', 'ggg']}

I want to combine all values into a single list -

 >>> ans = ['aaa', 'bbb', 'ccc', 'fff', 'ggg']

I can do this -

 >>> a = []
 >>> for v in d.values():
...   a.extend(v)
...
 >>> a
['aaa', 'bbb', 'ccc', 'fff', 'ggg']

I can also do this -

 >>> from itertools import chain
 >>> a = list(chain(*d.values()))
 >>> a
['aaa', 'bbb', 'ccc', 'fff', 'ggg']
 >>>

Is there a simpler way?

Thanks

Frank Millman




More information about the Python-list mailing list