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

Function reDict

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

Given aDict, return a new dict with valid items (= items whose cond(key, value) is true) been modified by the function func. if delUnchanged, then those invalid items are excluded from the returned dict. >>> d {'B': 1, 'D': 3} >>> reDict(d, lambda x:x**2) {'B':

(aDict, func, cond=(lambda k,v:1), delUnchanged=0)

Source from the content-addressed store, hash-verified

62#========================================================================
63
64def reDict(aDict, func, cond=(lambda k,v:1), delUnchanged=0):
65 '''
66 Given aDict, return a new dict with valid items (= items whose
67 cond(key, value) is true) been modified by the function func.
68 if delUnchanged, then those invalid items are excluded from
69 the returned dict.
70
71 >>> d
72 {'B': 1, 'D': 3}
73 >>> reDict(d, lambda x:x**2)
74 {'B': 1, 'D': 9}
75 >>> g
76 {'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3}
77 >>> reDict(g, lambda x:-x, lambda k,v: v%2==0)
78 {'A': 0, 'C': -2, 'B': 1, 'E': -4, 'D': 3}
79 >>> reDict(g, lambda x:-x, lambda k,v: v%2==0, delUnchanged=1)
80 {'A': 0, 'C': -2, 'E': -4}
81
82 '''
83 tmp={}
84 if delUnchanged:
85 [tmp.setdefault(k,func(v)) for k,v in aDict.items() if cond(k,v)]
86 else:
87 [tmp.setdefault(k,(cond(k,v) and func(v) or v)) for k,v in aDict.items()]
88 return tmp.copy()
89
90#========================================================================
91

Callers

nothing calls this directly

Calls 4

funcFunction · 0.50
setdefaultMethod · 0.45
itemsMethod · 0.45
copyMethod · 0.45

Tested by

no test coverage detected