2

Let's say I have a list of dicts or objects, which effectively looks like this:

[
    {'score': 5, 'tally': 6},
    {'score': 1, 'tally': None},
    {'score': None, 'tally': None},
]

What would be a Pythonic and concise way of creating a list of all ‘score’s and ‘tally’s that are not None? so the result would the following:

[5, 6, 1 ]

2 Answers 2

4

Try this concise solution, using list comprehensions:

lst = [{'score': 5, 'tally': 6},
       {'score': 1, 'tally': None},
       {'score': None, 'tally': None}]

[v for m in lst for v in m.values() if v is not None]
=> [6, 5, 1]
Sign up to request clarification or add additional context in comments.

4 Comments

This is really nice, thank you! do you know a similar method if the elements in the list aren't dicts? i.e. score and tally would be attributes on an object.
It'd be similar, because the attributes in an object are stored in the __dict__ attribute of the object
Note that this particular solution won't report if values are 0 or empty strings, etc. Other "falsy" values that aren't None. To find those as well, change the list comprehension to: [v for m in lst for v in m.values() if v is not None]
@brechin you're right, better to play it safe. I updated my answer, thanks!
1
list(i for i in 
     itertools.chain.from_iterable(
       itertools.izip_longest(
         (d['score'] for d in listOfDicts if d['score'] is not None), 
         (d['tally'] for d in listOfDicts if d['tally'] is not None)
     )) if i is not None)

>>> import itertools
>>> listOfDicts = [
...     {'score': 5, 'tally': 6},
...     {'score': 1, 'tally': None},
...     {'score': None, 'tally': None},
... ]
>>> list(i for i in itertools.chain.from_iterable(itertools.izip_longest((d['sco
re'] for d in listOfDicts if d['score'] is not None), (d['tally'] for d in listO
fDicts if d['tally'] is not None))) if i is not None)
[5, 6, 1]

3 Comments

Thanks, I never knew about izip_longest. This is similar to how my solution ended up, I just had the feeling I was missing out on a one line list comprehension.
Yeah, izip_longest comes in handy a lot. Check this out
Happy to help! As a side note, it's awesomely refreshing to be addressed by my real name. Usually, everyone just refers to everyone else by their usernames.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.