python - Try appending items to a default dictionary -
i have function:
#should named tryappendingtolistinadict i'm lazy long of name def tryappendingtodict(dictionary, key, item): try: #append existing list dictionary[key].append(item) except keyerror: #list doesn't exist yet, make 1 dictionary[key] = [item]
in cases use function on 1 dictionary, let's call defaultdictoflists
, in code looks like
tryappendingtodict(defaultdictoflists, 'spam', 'eggs') tryappendingtodict(defaultdictoflists, 'spam', 'beacon') tryappendingtodict(defaultdictoflists, 'not spam', 'yuck!') #... tryappendingtodict(differentdict, 'spam', 'i don't spam!')
so wanted try , make keyword argument function assume you're appending items defaultdictoflists
. however, main problem here, function imported separate module (and should remain there), simple
def tryappendingtodict(key, item, dictionary = defaultdictoflists):
raises nameerror
, , globals()['defaultdictoflists']
raises keyerror
.
is there way fix it? clarify code lot , speed coding process well.
edit
i'm not using defaultdict(list)
because dictionary passed django template , don't handle defaultdicts reason. i'd have convert defaultdict regular dict, takes o(n) time, if recall correctly.
why don't monkeypatch it? can:
from module import tryappendingtodict _tryappendingtodict def tryappendingtodict(key, item, dictionary=defaultdictoflists): return _tryappendingtodict(dictionary, key, item)
and use function in module defaultdictoflists
defined.
moreover, can't see usefulness of code, sure can use defaultdict
, can use dictionaries' setdefault
method. reduce dictionary insertions 1 line, turning tryappendingtodict()
useless:
>>>d={} >>>d.setdefault('key',['value']) >>>d {'key': ['value']}
Comments
Post a Comment