Finding a dictionary by a (unique) key in a python list

Written by Johannes on January 20, 2014 Categories: Uncategorized

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’ :).

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre user="" computer="" escaped="">