iNoob iNoob - 2 months ago 7
Python Question

Smarter way to gather data or a way to sort the data

I'm pulling data from an sqlite table using

snip1
, this of course grabs each row containing the relevant
id
value. The
services
list now looks like
output1
.

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
[(10, u'80'), (10, u'443')]
becomes
{10: 80, 443}
and of course all other entries added to the same
dict
.

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

snip1

c.execute('SELECT * FROM services WHERE id=?', (id_value,))
services = c.fetchall()


output1

[[(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')]]


example1

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


output2

(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')

Answer

You can do this with one line with using dict and list comprehensions

>>> 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')]]
>>> output = {record[0][0]: [int(item[1]) for item in record] for record in data}
>>> output
{2: [22],
 3: [25],
 4: [443],
 5: [443],
 6: [443],
 7: [22],
 8: [80],
 9: [443],
 10: [80, 443],
 11: [80, 443],
 12: [80, 443],
 13: [443],
 14: [80, 443],
 15: [25]}
Comments