Search code examples
pythonpython-datamodel

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


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.


Solution

  • 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'