开发者

What is the easiest way to search through a list of dicts in Python?

开发者 https://www.devze.com 2023-01-20 06:40 出处:网络
My database currently returns a list of dicts: id_list = ({\'id\': \'0c871320cf5111df87da000c29196d3d\'},

My database currently returns a list of dicts:

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

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

Thanks.


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.


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.


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'


any(x.get('id')==given_id for x in id_list)

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


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消