list comprehension (searching for onliners)

Max Erickson maxerickson at gmail.com
Fri Oct 20 14:58:01 CEST 2006


Gerardo Herzig <gherzig at fmed.uba.ar> 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.
> 
> Thanks dudes.
> Gerardo

Is three lines ok?

>>> output=dict()
>>> for record in result:
	output.setdefault(record['service_id'], list()).append(record
['value'])

	
>>> output
{1: [10, 15], 2: [5, 15]}
>>> 

Creating the more verbose output that you specified should be 
pretty straighforward from there.

max




More information about the Python-list mailing list