Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 341
nwly Avatar asked Jan 04 '17 04:01

nwly


2 Answers

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(), [])
like image 129
jez Avatar answered Oct 23 '22 14:10

jez


Use chain from itertools:

>>> from itertools import chain
>>> list(chain.from_iterable(test.values()))
# ['sunflower', 'maple', 'evergreen', 'dog', 'cat']
like image 12
Psidom Avatar answered Oct 23 '22 14:10

Psidom