views:

99

answers:

5

My database currently returns a list of dicts:

id_list = ({'id': '0c871320cf5111df87da000c29196d3d'}, 
           {'id': '2eeeb9f4cf5111df87da000c29196d3d'}, 
           {'id': '3b982384cf5111df87da000c29196d3d'}, 
           {'id': '3f6f3fcecf5111df87da000c29196d3d'}, 
           {'id': '44762370cf5111df87da000c29196d3d'}, 
           {'id': '4ba0d294cf5111df87da000c29196d3d'})

How can I easily check if a given id is in this list or not?

Thanks.

+2  A: 

You can flatten it with a list comprehension and use in:

id in [d['id'] for d in id_list]

You can also use generator expressions, which have different performance characteristics (and will use less memory if your list is huge):

id in (d['id'] for d in id_list)
Nathon
Thanks, which of these is more efficient?
ensnare
@ensnare: The second one, it will stop as soon as it finds the id. However, if you are going to do this often, put all ids into a set: `ids = set(d['id'] for d in id_list)` and then just check whether `givenId in ids`
eumiro
This was really helpful. Thank you.
ensnare
I explicitly left out the most efficient thing I could think of (which, in retrospect, is less efficient than @eumiro's set solution) because it's rather obfuscated and involves dicts and the question was "easiest". That said, I'm not convinced that the generator expression is most efficient in all cases. Certainly in this one, but if you're storing it and searching it repeatedly and it matters, you'd be better off measuring.
Nathon
+6  A: 

Here's a one-liner:

if some_id in [d.get('id') for d in id_list]:
    pass

Not very efficient though.

edit -- A better approach might be:

if some_id in (d.get('id') for d in id_list):
    pass

This way, the list isn't generated in full length beforehand.

Santiago Lezica
+4  A: 

if you make a dictionary of your search id,

search_dic = {'id': '0c871320cf5111df87da000c29196d3d'}

id_list = ({'id': '0c871320cf5111df87da000c29196d3d'}, 
           {'id': '2eeeb9f4cf5111df87da000c29196d3d'}, 
           {'id': '3b982384cf5111df87da000c29196d3d'}, 
           {'id': '3f6f3fcecf5111df87da000c29196d3d'}, 
           {'id': '44762370cf5111df87da000c29196d3d'}, 
           {'id': '4ba0d294cf5111df87da000c29196d3d'})


if search_dic in id_list:
    print 'yes'
joaquin
This was really helpful. Thank you.
ensnare
+3  A: 
any(x.get('id')==given_id for x in id_list)

. . . returns boolean. Efficiency? See S.Lott's answer

mshsayem
+5  A: 

How can I easily check if a given id is in this list or not?

Make a set

keys = set( d['id'] for d in id_list )
if some_value in keys

Don't ask if this is "efficient" or "best". It involves the standard tradeoff.

Building the set takes time. But the lookup is then instant.

  • If you do a lot of lookups, the cost of building the set is amortized over each lookup.

  • If you do few lookups, the cost of building the set may be higher than something ilike {'id':some_value} in id_list.

S.Lott