defaultdict not available, implementation using an empty dictionary
<p>I have a code that looks like this:</p>

<pre><code>abcd a1
abcd a2
abcd a3
abcd b1
abcd b2
q a1
q a2
</code></pre>

<p>I have a defaultdict implementation that places them in  dictionary. However, how would I do this without defaultdict(older python). My goal is to have a dictionary that looks something like this:</p>

<pre><code>abcd : 'a1','a2','a3','b1','b2'
q : 'a1', 'a2'
</code></pre>

<p>Also I need to count the number of elements in q, total number of elements in abcd and so on..</p>

<p>edited.</p>

<p>You can implement <code>__missing__</code> on a subclass of <code>dict</code> and create an additional <code>count</code> method to count the number of occurences of a key:</p>

<pre><code>class DefaultDict(dict):
    def __missing__(self, key):
        self[key] = []
        return self[key]

    def count(self, key):
        return len(self[key])

&gt;&gt;&gt; a = DefaultDict()
&gt;&gt;&gt; a['a'].append(1)
&gt;&gt;&gt; a['a'].append(1)
&gt;&gt;&gt; a['a'].append(1)
&gt;&gt;&gt; a['a'].append(1)
&gt;&gt;&gt; a['a'].append(1)
&gt;&gt;&gt; a
{'a': [1, 1, 1, 1, 1]}

&gt;&gt;&gt; a.count('a')
5
</code></pre>

python python-2.7