Search code examples
pythonfilterdefaultdict

Python filter defaultdict


I have a defaultdict of lists, but I want to basically do this:

myDefaultDict = filter(lambda k: len(k)>1, myDefaultDict)

Except it only seems to work with lists. What can I do?


Solution

  • Are you trying to get only values with len > 1?

    Dictionary comprehensions are a good way to handle this:

    reduced_d = {k: v for k, v in myDefaultDict.items() if len(v) > 1}
    

    As martineau pointed out, this does not give you the same defaultdict functionality of the source myDefaultDict. You can use the dict comprehension on defaultdict instantiaion, as martineau shows to get the same defaultdict functionality.

    from collections import defaultdict
    
    myDefaultDict = defaultdict(list, {'ab': [1,2,3], 'c': [4], 'def': [5,6]})  # original 
    reduced_d = defaultdict(list, {k: v for k, v in myDefaultDict.items() if len(v) > 1})