Concatenation of dict values ​​that 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'] 

what I want.

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

+5
source share
4 answers

You almost answered the question: sum(test.values()) fails, because by default it is assumed that you want to add elements to the initial value 0 - and, of course, you cannot add list to int . However, if you explicitly specify an initial value, it will work:

  sum(test.values(), []) 
+7
source

Use chain from itertools :

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

One insert (no special order required):

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

You can use functools.reduce and operator.concat (I assume you are using Python 3) as follows:

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

Source: https://habr.com/ru/post/1262256/


All Articles