Dictionary value initialization on lookup
Question: 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.


Answer: You can use
[dict.setdefault](http://www.tutorialspoint.com/python/dictionary_setdefault.htm)

    
    
    mylist = ['a','b','c','d']
    mydict = {}
    for val in mylist:
        mydict.setdefault(val,[])
        mydict[val].append(1)
    

Or use
[collections.defaultdict](https://docs.python.org/2/library/collections.html#collections.defaultdict)
which is more efficient

    
    
    from collections import defaultdict
    mylist = ['a','b','c','d']
    mydict = defaultdict(list)
    for val in mylist:
        mydict[val].append(1)
    
    
    In [14]: mylist = ['a','b','c','d']    
    In [15]: mydict = {}    
    In [16]: %%timeit
       ....: for val in mylist:
       ....:     mydict.setdefault(val,[])
       ....:     mydict[val].append(1)
       ....: 
    1000000 loops, best of 3: 1.51 µs per loop
    
    In [18]: mydict = defaultdict(list)
    In [19]: %%timeit
       ....: for val in mylist:
       ....:     mydict[val].append(1)
       ....: 
    1000000 loops, best of 3: 603 ns per loop
    

