Search code examples
pythonlistlist-comprehension

Append to list if not None, within a list comprehension


I have a dictionary containing some None values under a key, like:

tmp = {"frames": ['0', '12', '56', '35', None, '77', '120', '1000']}

I need to create a list of elements from the dict, under the "frame" key, which are not None (None should be left out). The explicit way is to do:

for frame in tmp['frames']:
    if frame:
        output.append(frame)

But I was wondering if there's a one-liner expression to do the same. I could think of something like:

output = [frame if frame else None for frame in tmp['frames']]

but this way, I don't know how to exclude the None values


Solution

  • You can use if condition in list comprehension

    [int(value) for value in tmp['frames'] if value is not None]