List comprehension from dict of lists

  • A+
Category:Languages

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?

 


You were almost there. The main problem you were facing is due to the order of the for loop.

The order of for loop inside the list comprehension is based on the order in which they appear in traditional loop approach. Outer most loop comes first, and then the inner loops subsequently.

a = {'b': [1,2,3], 'c':[4,5,6]} x = [] for k, v in a.items():     for i in v:         x.append([k, i])  print(x)  print([[k,i] for i in v for k, v in a.items()]) print([[k,i] for k, v in a.items() for i in v]) 

OUTPUT

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: