Filter list of dictionaries

前端 未结 5 560
既然无缘
既然无缘 2021-01-13 08:40

This is my example:

dictlist = [{\'first\': \'James\', \'last\': \'Joule\'}, 
            {\'first\': \'James\',\'last\': \'Watt\'},
            {\'first\':          


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 09:00

    I sometimes like to use next:

    next((d['last'] for d in dictlist if d['first'] == 'Christian'), None)
    # 'Doppler'
    

    The first argument is an iterator and the second (optional) argument is the default value returned if no matching entry is found.

    Note: this will only return the first matching result. So it wouldn't be good if you expect to have multiple records matching your "query".

提交回复
热议问题