Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension from dict of lists

I have a dict-

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

I want to use list comprehension only to achieve this output-

[['c', 4], ['c', 5], ['c', 6], ['b', 1], ['b', 2], ['b', 3]]

A simple for loop gets it done with -

x = []
for k, v in a.iteritems():
    for i in v:
        x.append([k, i])

Tried to convert it to list comprehension, I did this-

[[k,i] for i in v for k, v in a.items()]

But weirdly for me, I got an output

[['c', 1], ['b', 1], ['c', 2], ['b', 2], ['c', 3], ['b', 3]]

What should be the right list comprehension and why is my list comprehension not working?

like image 518
Sushant Avatar asked Dec 06 '22 11:12

Sushant


1 Answers

b = [[i, j] for i in a for j in a[i]]

for nested for loops in list comprehension the first loop will be the one whose variable you will be using in the second one, like here for example i is used in the second loop, nested for loops in list comprehensions are hard to read therefore you should better avoid it.

like image 191
Mohit Solanki Avatar answered Dec 26 '22 16:12

Mohit Solanki