Your ads will be inserted here by
Easy AdSense.
Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.
Given an iterable of dictionaries of the form
l = ( { 'id' : 1, 'data': 'some random data'}, { 'id' : 2, 'data': 'other random data'}, { 'id' : 4, 'data': 'more random data'}, ) |
we can find a particular item in the list by key with this lispish looking one-liner:
(lambda a: list(a)[0])(x for x in l if x['id']==2) |
Your ads will be inserted here by
Easy AdSense.
Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.
Obviously we could also just use this one:
[x for x in l if x['id']==2][0] |
but that would destroy the joy of using an unnecessary lambda :D.
Even more beautiful is what I found on StackExchange (http://stackoverflow.com/a/9542768/1945909):
next(x for x in l if x['id']==2) |
Now imagine the beautiful oneliner we could get if we knew the list was sorted by ‘id’ :).
Leave a Reply