convert a list to dict with key equal to every unique item and value equal to the indices of the item in the list
<p>For example, I have a list of <code>a = ['a', 'b', 'a']</code>, what is the best code to convert it to <code>b = {'a': [0, 2], 'b': [1]}</code>?</p>

<p>You can use <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> with <code>list</code> default factory:</p>

<pre><code>&gt;&gt;&gt; from collections import defaultdict
&gt;&gt;&gt; a = ['a', 'b', 'a']
&gt;&gt;&gt; res = defaultdict(list)
&gt;&gt;&gt; for i, s in enumerate(a):
...     res[s].append(i)
... 
&gt;&gt;&gt; res
defaultdict(&lt;type 'list'&gt;, {'a': [0, 2], 'b': [1]})
</code></pre>

<p>Parameter given to <code>defaultdict</code> is a function that will be called to provide initial value in case that given key doesn't exist. Since original list is being iterated once and time complexity of <code>list.append</code> is <strong>O(1)</strong> the total time complexity is <strong>O(n)</strong>.</p>

<p><strong>Update</strong> Performance comparison of different solutions:</p>

<pre><code>from collections import defaultdict

def test1(l):
    b = dict.fromkeys(set(l), [])
    for i, val in enumerate(l):
       b[val] = b.get(val)+[i]

def test2(l):
    res = defaultdict(list)
    for i, s in enumerate(l):
        res[s].append(i)

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test1(['a'] * 1000)", setup="from __main__ import test1", number=10))
    print(timeit.timeit("test2(['a'] * 1000)", setup="from __main__ import test2", number=10))
</code></pre>

<p>Output:</p>

<pre><code>0.03234261799661908
0.000929353991523385
</code></pre>

python