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>Instead of <code>defaultdict</code> use <code>setdefault()</code>:</p>

<pre><code>x = {}
x.setdefault('abcd', []).append('a1')
x.setdefault('abcd', []).append('a2')
</code></pre>

<p>This will result in:</p>

<pre><code>abcd: ['a1', 'a2']
</code></pre>

<p>and works by trying to lookup <code>'abcd'</code> as key for <code>x</code> and when not avaialable, initiating it as an empty list (<code>[]</code>). and return either the found value or the newly instantiated list. The <code>.append()</code> works on the returned value (first time on the empty list, after that on the list with <code>a1</code>).</p>

<p>I am not sure when this was added but I have code from 2001 which uses <code>setdefault()</code> so your Python version will probably support this.</p>

python python-2.7