MCPcopy Create free account
hub / github.com/ActiveState/code / trimDict

Function trimDict

recipes/Python/278259_Dictionary_Tools/recipe-278259.py:47–60  ·  view source on GitHub ↗

Return a new dict in which its items whose cond(k,v) == true are removed (discarded) from aDict. The cond is a function taking 2 arguments: key and value >>> g {'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3} >>> trimDict(g, lambda x,y:y%2!=0) {'A': 0, 'C': 2, 'E': 4}

(aDict, cond=(lambda k,v:1))

Source from the content-addressed store, hash-verified

45#========================================================================
46
47def trimDict(aDict, cond=(lambda k,v:1)):
48 ''' Return a new dict in which its items whose cond(k,v) == true
49 are removed (discarded) from aDict.
50 The cond is a function taking 2 arguments: key and value
51
52 >>> g
53 {'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3}
54 >>> trimDict(g, lambda x,y:y%2!=0)
55 {'A': 0, 'C': 2, 'E': 4}
56
57 '''
58 tmp={}
59 [tmp.setdefault(k,v) for k,v in aDict.items() if not cond(k,v)]
60 return tmp.copy()
61
62#========================================================================
63

Callers

nothing calls this directly

Calls 3

setdefaultMethod · 0.45
itemsMethod · 0.45
copyMethod · 0.45

Tested by

no test coverage detected