What is the most elegant way to create a dictionary with the value as lists?
<p>So I have something like</p>

<pre><code>retval = {}

# ...
# some code here to fetch data
# ...

for row in cursor.fetchall():
    if row.someid not in retval:
        retval[row.someid] = [dict(zip(columns,rows))]
    else:
        retval[row.someid].append(dict(zip(columns,rows))
</code></pre>

<p>which yields:</p>

<pre><code>retval = {
    1: [{'someid': 1, 'samplefield': 'valueX', ... },
        {'someid': 1, 'samplefield': 'valueY', ... }],
    2: [{'someid': 2, 'samplefield': 'valueX', ... }]
    }
</code></pre>

<p>I feel like there is a much more pythonic way to attain the result that I need.</p>

<p>To be precise, is there a way to reduce these lines of code:</p>

<pre><code>if row.someid not in retval:
    retval[row.someid] = [dict(zip(columns,rows))]
else:
    retval[row.someid].append(dict(zip(columns,rows))
</code></pre>

<p>to be in a single line?</p>

<p><strong>Answer:</strong>
It was in the <a href="https://docs.python.org/2/library/collections.html#defaultdict-examples" rel="nofollow">docs</a> all along! Thank you to <a href="http://stackoverflow.com/users/2797476/christian-ternus">Christian Ternus</a> &amp; <a href="http://stackoverflow.com/users/1648033/chthonicdaemon">chthonicdaemon</a> for pointing me in the right direction. I updated this cause I found that there could be multiple ways of doing it based on the docs.</p>

<pre><code>from collections import defaultdict
retval = defaultdict(list) ## Or retval = defaultdict(lambda: []) based on my accepted answer.

# ...
# some code here to fetch data
# ...

for row in cursor.fetchall():
    retval[row.someid].append(dict(zip(columns,rows))
</code></pre>

<p><strong><em>OR</em></strong> </p>

<pre><code>retval = {} 

# ...
# some code here to fetch data
# ...

for row in cursor.fetchall():
    retval.setdefault(row.someid, []).append(dict(zip(columns,rows))
</code></pre>

<p>Hopes this helps you as much as it helped me!</p>

<p>Try using <code>defaultdict</code> from the builtin <code>collections</code> module:</p>

<pre class="lang-python prettyprint-override"><code>from collections import defaultdict
retval = defaultdict(lambda: [])

# ...
# some code here to fetch data
# ...

for row in cursor.fetchall():
    retval[row.someid].append(dict(zip(columns,rows))
</code></pre>

python