any suggestion on this code

Ganesh Pal ganesh1pal at
Sun Apr 23 04:21:27 EDT 2017

Hello  Team,

I have a sample code that runs through the list of dictionary and return a
dictionary if the search  value matched

*Sample Program:*


def return_matched_owner(dict_list,search_block):

    """Accepts a list of dictionary with owners and returns a dict if there
is a match"""


        x = next(item for item in dict_list if item.get("Block") ==

    except StopIteration:

        return False

    return x

def main():

    dict_list = [{'real_owner': '1:0070', 'fake_owner': '121212aaa',
'Block': '121212121'},

                 {'real_owner': '1:0170', 'fake_owner': 'aaabbbb', 'Block':

                 {'real_owner': '1:0120', 'fake_owner': 'accccb', 'Block':

    x =  return_matched_owner(dict_list,'31115674')

    print x

    if not x:

       assert False, "Error while getting owner"

    print "\n Matching owner found \n"

if __name__ == '__main__':


*Sample o/p:*

yy-1# python

{'real_owner': '1:0120', 'fake_owner': 'accccb', 'Block': '31115674'}

 Matching owner found

Couple of question here :

1.      Any better suggestion to optimize the code  and any other
observations  around use of assert, generators  and are exception handled
correctly in  return_matched_owner()



More information about the Python-list mailing list