List comprehension vs filter()
rosuav at gmail.com
Wed Apr 20 05:10:21 CEST 2011
Context: Embedded Python interpreter, version 2.6.6
I have a list of dictionaries, where each dictionary has a "type"
element which is a string. I want to reduce the list to just the
dictionaries which have the same "type" as the first one.
I'm seeing a weird difference between two otherwise-equivalent-looking
ways of doing the job.
lst=filter(lambda x: x["type"].lower()==type,lst) # Restrict to that one type
lst=[i for i in lst if i["type"].lower()==type] # Restrict to that one type
If I use the filter() method, the resulting list is completely empty.
If I use the list comprehension, it works perfectly. Oddly, either
version works in the stand-alone interpreter.
I have no idea where to start looking for the problem. Hints, please!
More information about the Python-list