Gerardo Herzig wrote: > Hi all: I have this list thing as a result of a db.query: (short version) > result = [{'service_id' : 1, 'value': 10}, > {'service_id': 2, 'value': 5}, > {'service_id': 1, 'value': 15}, > {'service_id': 2, 'value': 15}, > ] > > and so on...what i need to do is some list comprehension that returns me > something like > > result = [ > { > 'service_id' : 1, 'values': [ {'value': 10}, > {'value': 15}] > }, > { > 'service_id' : 2, 'values': [ {'value': 5}, {'value': 15}] > } > > > My problem now is i cant avoid have "repeteated" entries, lets say, in > this particular case, 2 entries for "service_id = 1", and other 2 for > "service_id =2". > Ill keeping blew off my hair and drinking more cofee while searching for > this damn onliner im looking for.
If you import itertools and have your DB query return in order of service_id (or sort the list after retrieving result), then... [ [dict(service_id=key),[dict(value=n['value']) for n in value]] for key,value in itertools.groupby(result,lambda x: x['service_id']) ] ... is more or less what you want. Jon. -- http://mail.python.org/mailman/listinfo/python-list