Reading Database Queries into a Specific format in Python
<p>Hi I'm connecting to sqlite database using python and fetching some results. However to input these results to another file I need it to be in the following format.</p>

<pre><code>     x={
     (1,1):1, (1,2):0,  
     (2,1):1, (2,2):0, 
     (3,1):0, (3,2):1, 
     (4,1):0, (4,2):1,}
</code></pre>

<p>My database table has only two rows (id (integer) and task (integer)). So I run the query "select * from allocation" and the result I get required to be formatted as above.</p>

<p>For instance allocation table is as follows:</p>

<pre><code>    id | task
    1  | 1
    2  | 1
    3  | 2
    4  | 2
</code></pre>

<p>Please Help.</p>

<p>In this code the commented lines at the top indicate what's needed to access the sqlite database. Since I didn't want to build and populate such a database I created the object <strong>C</strong> to emulate its approximate behaviour. I used <strong>defaultdict</strong> because I don't know how many possible combinations of id's and tasks are involved. However, this means that only non-zero occurrences are represented in the final dictionary.</p>

<pre><code>#~ import sqlite3

#~ conn = sqlite3 . connect ( some database )
#~ c = conn . cursor ( )
#~ c . execute ( 'Select id, task from aTable' ) 

class C:
    def __init__(self,iterated):
        self.iterated=iterated
    def fetchone (self):
        for _ in iter(list(self.iterated)):
            yield _

c=C( [ ['1','1'], ['2','1'], ['3','2'], ['4','2'] ] )

from collections import defaultdict

counts = defaultdict(int)
for row in c.fetchone():
    print (row)
    id, task = row
    counts [(id,task)]+=1

print (counts)
</code></pre>

<p>Here's the output.</p>

<pre><code>['1', '1']
['2', '1']
['3', '2']
['4', '2']
defaultdict(&lt;class 'int'&gt;, {('4', '2'): 1, ('2', '1'): 1, ('1', '1'): 1, ('3', '2'): 1})
</code></pre>

python