简体   繁体   中英

First non-null value from a list of dicts

Let's suppose that I want to get the first value of key that is not null inside this list of dicts:

arr = [
    {
      "key": None,
      "anotherkey": 0
    },
    {
      "another": "ignore"
    },
    {
      "bool": True,
      "key": "this!"
    }
  ]

Is there some one-liner to do this? I made it using a for loop.

You can loop over the inner dictionaries and check for a key that isn't None using a generator expression within next :

>>> next((d['key'] for d in arr if d.get('key') is not None), None)
'this!'

This will return the first value associated with 'key' , otherwise None if no such key/value pairs exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM