Smarter way to gather data or a way to sort the data
<p>I'm pulling data from an sqlite table using <code>snip1</code>, this of course grabs each row containing the relevant <code>id</code> value. The <code>services</code> list now looks like <code>output1</code>.</p>

<p>I'd like to be able to sort the list of lists of tuples into a more managable data set. Merging all relevant id sets.
For example <code>[(10, u'80'), (10, u'443')]</code> becomes <code>{10: 80, 443}</code> and of course all other entries added to the same <code>dict</code>.</p>

<p>I'm having a hard time sorting the data. How would I compare items in the same list? The <code>example1</code> below shows the data cleaned up, but I'm uncertain on how to achieve a clean dictionary from it.</p>

<p><strong>snip1</strong></p>

<pre><code>c.execute('SELECT * FROM services WHERE id=?', (id_value,))
services = c.fetchall()
</code></pre>

<p><strong>output1</strong></p>

<pre><code>[[(2, u'22')], [(3, u'25')], [(4, u'443')], [(5, u'443')], [(6, u'443')], [(7, u'22')], 
[(8, u'80')], [(9, u'443')], [(10, u'80'), (10, u'443')], [(11, u'80'), (11, u'443')], 
[(12, u'80'), (12, u'443')], [(13, u'443')], [(14, u'80'), (14, u'443')], [(15, u'25')]]
</code></pre>

<p><strong>example1</strong></p>

<pre><code>data = [(2, u'22')], [(3, u'25')], [(4, u'443')], [(5, u'443')], [(6, u'443')], [(7, u'22')], 
    [(8, u'80')], [(9, u'443')], [(10, u'80'), (10, u'443')], [(11, u'80'), (11, u'443')], 
    [(12, u'80'), (12, u'443')], [(13, u'443')], [(14, u'80'), (14, u'443')], [(15, u'25')]]

for item in data:
    for i in item:
        print i  #output2
</code></pre>

<p><strong>output2</strong></p>

<pre><code>(2, u'22')
(3, u'25')
(4, u'443')
(5, u'443')
(6, u'443')
(7, u'22')
(8, u'80')
(9, u'443')
(10, u'80')
(10, u'443')
(11, u'80')
(11, u'443')
(12, u'80')
(12, u'443')
(13, u'443')
(14, u'80')
(14, u'443')
(15, u'25')
</code></pre>

<p>To convert a list of tuples into a dictionary:</p>

<pre><code>    list = [(10, u'80'), (10, u'443')]
    dict = {}

    for (i, j) in list:
        dict.setdefault(i, []).append(j)
</code></pre>

<p>This will give you:</p>

<pre><code>    &gt;&gt;&gt; dict
    {10: [u'80', u'443']}
</code></pre>

<p>You can then use pprint to print in a way that it is easy to compare dictionary items. </p>

<pre><code>    import pprint
    pprint.pprint(dict)
</code></pre>

<p>The example only has one key but pprint will make a new row for each key similiar to what you have up there.</p>

python dictionary