Filter list of dictionaries

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

This is my example:

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


        
相关标签:
5条回答
  • 2021-01-13 08:53

    This is very simple solution with list comprehension:

    >>> dictlist = [{'first': 'James', 'last': 'Joule'}, {'first': 'James','last': 'Watt'},{'first': 'Christian','last': 'Doppler'}]
    >>> [x['last'] for x in dictlist if x['first'] == 'Christian']
    ['Doppler']
    
    0 讨论(0)
  • 2021-01-13 08:58
    for comp in dictlist:
        if comp["first"] == 'Christian':
            return comp["last"]
    
    0 讨论(0)
  • 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".

    0 讨论(0)
  • 2021-01-13 09:06
    dictlist = [{'first': 'James', 'last': 'Joule'}, {'first': 'James','last': 'Watt'},{'first': 'Christian','last': 'Doppler'}]
    the_jameses = [d for d in dictlist if d['first'] == 'James']
    

    Where the resulting list contains only:

    [{'first': 'James', 'last': 'Joule'}, {'first': 'James', 'last': 'Watt'}]
    
    0 讨论(0)
  • 2021-01-13 09:11

    Something like this should work

    last_name = ''
    
    for d in dictList:
      if d['first'] == 'Christian':
        last_name = d['last']
        break
    
    0 讨论(0)
提交回复
热议问题