python filter list of dictionaries based on key value

后端 未结 2 1969
醉梦人生
醉梦人生 2020-11-27 02:44

I have a list of dictionaries and each dictionary has a key of (let\'s say) \'type\' which can have values of \'type1\', \'type2\', etc. My goal is

相关标签:
2条回答
  • 2020-11-27 03:34

    You can try a list comp

    >>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
    >>> keyValList = ['type2','type3']
    >>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
    >>> expectedResult
    [{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
    

    Another way is by using filter

    >>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
    [{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
    
    0 讨论(0)
  • 2020-11-27 03:35

    Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

    from itertools import ifilter
    for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
        print elem
    
    0 讨论(0)
提交回复
热议问题