Python: Collapsing a dict with list values into a single list
Suppose you have something like so:
my_dict = {
'key1' : ['val11', 'val12', 'val13'],
'key2' : ['val21', 'val22', 'val23']
}
— i.e., a dictionary with lists as the values. Suppose you want to collapse this dict into a single list. You could do it like so:
my_list = list()
for key in my_dict.iterkeys():
my_list.extend( my_dict[key] )
but there’s a nicer way using list comprehensions:
my_list = list()
[my_list.extend(x) for x in my_dict.itervalues()]
Initially that looked like a mistake to me — as though the second line would return a new list, do nothing with it, silently drop it and leave my_list empty. But in fact that second line does just what you’d think. I find it cute.
Comments Off