2
d = {'a':[1,2,3], 'b':[4,5]} 

and I need

[1,2,3,4,5] 

using list comprehension. How do I do it?

2
  • 1
    Do you want the output in any particular order? (Python dictionaries are not intrinsically sorted.) Commented Jan 18, 2017 at 6:04
  • Order is not important Commented Jan 18, 2017 at 6:08

4 Answers 4

6

Use a nested list comprehension:

>>> [val for lst in d.values() for val in lst]
[1, 2, 3, 4, 5]

But you may need to sort the dictionary first (because dicts are unordered) to guarantee the order:

>>> [val for key in sorted(d) for val in d[key]]
[1, 2, 3, 4, 5]
Sign up to request clarification or add additional context in comments.

3 Comments

No. Sorting the list comp is better.
@MYGz That depends, I assumed he wanted to get all the values depending on the (sorted) order of the keys. Not sort all the values for all keys.
Thats right. Sort by key or sort by values. And 1 more possibility sort by both :)
1

Easy and one liner solution using list comprehension:

>>> sorted([num for val in d.values() for num in val])
    [1, 2, 3, 4, 5]

Comments

1

sum(d.values(),[]) works but not performant because it applies a = a + b for each temp list.

Use itertools.chain.from_iterable instead:

import itertools
print(list(itertools.chain.from_iterable(d.values())))

or sorted version:

print(sorted(itertools.chain.from_iterable(d.values())))

4 Comments

chain.from_iterable is probably better and faster than unpacking (*d.values()).
why do I always forget that?
Probably because it's more to type :-)
:) lesson learned. One should be alarmed when there's too many symbols in an answer...
0

If the order of elements is not important, then you cannot beat this:

sum(d.values(), [])

(Add sorted() if necessary.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.