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?
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(), [])
Use chain
from itertools
:
>>> from itertools import chain
>>> list(chain.from_iterable(test.values()))
# ['sunflower', 'maple', 'evergreen', 'dog', 'cat']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With