list comprehension (searching for onliners)

G

Gerardo Herzig

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
 
J

Jon Clements

Gerardo said:
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.
 
R

Roberto Bonvallet

Gerardo Herzig wrote:
[...]
and so on...what i need to do is some list comprehension that returns me
something like
[...]

You don't _need_ a list comprehension, you just _want_ one :)

[...]
Ill keeping blew off my hair and drinking more cofee while searching for
this damn onliner im looking for.

I know, trying to put complex logic in one line makes you do all that.

Go for the multiliner!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top