Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 341
Paul Stanley Avatar asked Oct 28 '25 18:10

Paul Stanley


1 Answers

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})
like image 200
monkut Avatar answered Oct 31 '25 08:10

monkut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!