using defaultdict in a array in python 2.7
<p>I'm trying to create a dictionary where the same key can have different values from an array. In the past i created a dictionary with positions on each list of the list, but I found a bug where the same key can have more than one value and it's breaking the main code.
ie.</p>

<pre><code>my_array = [['a','b','c'],['a','e','d'],['f','g','h']]
my dict = dict([p[0], p[2]] for p in my_array)
my dict = {'a': 'c', 'f': 'h'}
What I need is:
my_dict = {'a': ['c','d'], 'f': 'h'}
</code></pre>

<p>I have tried with defaultdict but so far I'm getting TypeError Exception. I have tried initializing it as a string defaultdict(str) and a list defaultdict(list) with no success</p>

<pre><code>my_dict = defaultdict((my_dict[p[0]].append(p[2])) for p in my_array)
or
my_dict = defaultdict(([p[0], p[2]]).append(p[2]) for p in a_array)
</code></pre>

<p>Always getting TypeError exception, suggestions please?</p>

<p>The <code>defaultdict</code> contructor takes a <em>callable</em> that will service as the default value for any undefined key. In your case, the default value is simply a <code>list</code>.</p>

<p>This code does what you want:</p>

<pre><code>from collections import defaultdict
my_dict = defaultdict(list)
for p in [['a','b','c'],['a','e','d'],['f','g','h']]:
    my_dict[p[0]].append(p[2])
my_dict = dict(my_dict)
</code></pre>

python python-2.7