18
votes

Suppose I have the following dict object:

test = {}
test['tree'] = ['maple', 'evergreen']
test['flower'] = ['sunflower']
test['pets'] = ['dog', 'cat']

Now, if I run test['tree'] + test['flower'] + test['pets'], I get the result:

['maple', 'evergreen', 'sunflower', 'dog', 'cat']

which is what I want.

However, suppose that I'm not sure what keys are in the dict object but I know all the values will be lists. Is there a way like sum(test.values()) or something I can run to achieve the same result?

5

5 Answers

34
votes

You nearly gave the answer in the question: sum(test.values()) only fails because it assumes by default that you want to add the items to a start value of 0—and of course you can't add a list to an int. However, if you're explicit about the start value, it will work:

 sum(test.values(), [])
10
votes

Use chain from itertools:

>>> from itertools import chain
>>> list(chain.from_iterable(test.values()))
# ['sunflower', 'maple', 'evergreen', 'dog', 'cat']
8
votes

One liner (assumes no specific ordering is required):

>>> [value for values in test.values() for value in values]
['sunflower', 'maple', 'evergreen', 'dog', 'cat']
4
votes

You could use functools.reduce and operator.concat (I'm assuming you're using Python 3) like this:

>>> from functools import reduce
>>> from operator import concat
>>> reduce(concat, test.values())
['maple', 'evergreen', 'sunflower', 'dog', 'cat']
0
votes

Another easy option using using numpy.hstack:

import numpy as np

>>> np.hstack(list(test.values()))
array(['maple', 'evergreen', 'sunflower', 'dog', 'cat'], dtype='<U9')