如何用Python的filter函数替代循环实现字典列表查找功能?
Hey there, let's fix this issue with filter()! The problem you're hitting is that in Python 3, filter() returns an iterator object — not a dictionary or list — so you can't directly subscript it with ['name']. Let's adjust your code to match the behavior of your original getAssignee() function step by step.
核心问题解释
Your original function loops through assigneeList, stops at the first item where title matches keyTitle, returns its name, and returns an empty string if no match is found. The filter() function doesn't return a single matching item right away — it creates an iterator that yields all matching items. To replicate your original logic, we need to grab the first (and only, assuming titles are unique) matching item from this iterator, then handle the case where no match exists.
解决方案1:使用next()高效获取首个匹配项
This is the most efficient approach, as it stops searching as soon as it finds the first match (just like your original break statement):
def getAssignee(keyTitle): # Use next() to get the first matching item, default to None if no match matched_item = next(filter(lambda item: item['title'] == keyTitle, assigneeList), None) # Return the name if we found a match, else return empty string return matched_item['name'] if matched_item else ''
解决方案2:转换为列表后取首个元素
If you prefer working with lists, you can convert the filter iterator to a list first. Note that this will process all items in the list even after finding a match, so it's less efficient for large datasets:
def getAssignee(keyTitle): # Convert filter results to a list matched_items = list(filter(lambda item: item['title'] == keyTitle, assigneeList)) # Return the name of the first item if list isn't empty, else empty string return matched_items[0]['name'] if matched_items else ''
测试示例
Using your sample assigneeList:
assigneeList = [{'title':'Book', 'name':'Davis'},{'title':'TV','name':'Samsung'}] print(getAssignee('TV')) # Output: Samsung print(getAssignee('Phone')) # Output: (empty string)
内容的提问来源于stack exchange,提问作者thandasoru

