I have a function:
#Should be named tryAppendingToListInADict but I'm too lazy for that long of a name
def tryAppendingToDict(dictionary, key, item):
try:
#append to an existing list
dictionary[key].append(item)
except KeyError:
#list doesn't exist yet, so make one
dictionary[key] = [item]
In most cases I use this function on one dictionary, let's call it defaultDictOfLists
, as in my code looks like
tryAppendingToDict(defaultDictOfLists, 'spam', 'eggs')
tryAppendingToDict(defaultDictOfLists, 'spam', 'beacon')
tryAppendingToDict(defaultDictOfLists, 'not spam', 'yuck!')
#...
tryAppendingToDict(differentDict, 'spam', 'I don't like spam!')
So I wanted to try and make a keyword argument to my function that would assume you're appending items to the defaultDictOfLists
. However, the main problem here, is that this function is imported from a separate module (and should remain there), so a simple
def tryAppendingToDict(key, item, dictionary = defaultDictOfLists):
raises a NameError
, and globals()['defaultDictOfLists']
raises a KeyError
.
Is there a way to fix it? It would clarify my code a lot and speed up the coding process as well.
Edit
I'm not using defaultdict(list)
because this dictionary is passed to a Django template and those don't handle defaultdicts very well for some reason. So I'd have to convert this defaultdict back to a regular dict, which takes O(n) time, if I recall correctly.