Python single line stores list values ​​in dict to list

I would like to write a for loop in one line:

d = {'a': [1, 2, 3], 'b': [5, 6, 7], 'c': [9, 0]}

my_list = []
for k, v in d.items():
    for x in v:
        my_list.append(x)

How can i do this?

+5
source share
4 answers
>>> d = {'a': [1, 2, 3], 'b': [5, 6, 7], 'c': [9, 0]}
>>> [y for x in d.values() for y in x]
[1, 2, 3, 9, 0, 5, 6, 7]

This is an embedded understanding. To show how this works, you can split it into lines to see its structure as nested loops for. It goes from left to right.

[y 
 for x in d.values() 
 for y in x]
+9
source
list(itertools.chain(*d.values()))

As @jamylak suggested, the following may be more efficient, since it avoids the complete unpacking performed by the statement *:

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

In python 2.x use .itervaluesinstead .valuesto avoid unnecessarily copying lists.

+1
source

What about

ll = []
for l in d.values(): 
    ll.extend(u)
+1
source

Using operator overload -

sum(d.values(), [])
0
source

All Articles