Tuesday, September 06, 2005

oneliner: Flatten a dict with lists

How nice and simple this is:

Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {'a':[1], 'b':[2,3], 'c':[4,5,6]}
>>> sum(d.values(), [])
[1, 4, 5, 6, 2, 3]

That's because sum can use a start value :)
>>> help(sum)
Help on built-in function sum:

sum(...)
sum(sequence, start=0) -> value

Returns the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start'. When the sequence is empty, returns start.