Skip to content Skip to sidebar Skip to footer

Concatenating Dict Values, Which Are Lists

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

Solution 1:

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(), [])

Solution 2:

Use chain from itertools:

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

Solution 3:

One liner (assumes no specific ordering is required):

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

Solution 4:

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

Solution 5:

Another easy option using using numpy.hstack:

import numpy as np

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

Post a Comment for "Concatenating Dict Values, Which Are Lists"