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?
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.
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