1

This is my dict and list

d = {1: ['val1', 'val2'], 2: ['val3', 'val4']}
l = []

for key, value in d.items():
    for sub_value in value:
        l.append(sub_value)

print (l)

# ['val1', 'val2', 'val3', 'val4']


However, I would like to do this with dict to list comprehension.

I have something like this,

l = [sub_value for sub_value in value for key,value in d.items()]

Also tried,

l = [(sub_value for sub_value in value) for key,value in d.items()]

However, not quite the answer I was looking for.

Thanks.

  • Note that "dict into list comprehension" is not a thing. This is a list comprehension that happens to iterate over a dict -- it's no less of a list comprehension because of this. – Adam Smith Oct 17 '18 at 22:45

3 Answers3

2

You were pretty close with the first one; just the wrong order:

In [42]: [el for v in d.values() for el in v]
Out[42]: ['val1', 'val2', 'val3', 'val4']
Randy
  • 14,349
  • 2
  • 36
  • 42
1

Use the following list comprehension:

l = [j for i in d for j in d[i]]

>>> d = {1: ['val1', 'val2'], 2: ['val3', 'val4']}
>>> l = [j for i in d for j in d[i]]
>>> l
['val1', 'val2', 'val3', 'val4']
>>> 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
1

I will be the first to admit that list comprehension sure is confusing sometimes:

[sub_value for key,value in d.items() for sub_value in value]

This gives the required output.

Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
  • 1
    Ah, just moving the orders around can work with for loops in another for loop. Thanks. –  Oct 17 '18 at 21:18