Consider the following:
mylist = ['a','b','c','d']
mydict = {}
for val in mylist:
if val not in mydict:
mydict[val] = []
mydict[val].append(1)
Is there any way to avoid the double lookup ("val in mydict
" and "mydict[val]
")?
Note - I've tried using a default return value (i.e. mydict.get(val, []).append(1)
), but the new list isn't actually registered in the dictionary as the value for the key. For example:
mydict = {}
mydict.get('not_in_dict','default')
mydict
returns {}
. In my case I want something that would return {'not_in_dict' : 'default'}
.
Or is the correct answer here that I should't worry about double lookups? (e.g. "chill, dude, don't optimize if you don't have to" or "python is awesome, it takes care of this already").
I'm using python 3.4.