any suggestion on this code

Ganesh Pal ganesh1pal at gmail.com
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:*



#!/usr/bin/python



def return_matched_owner(dict_list,search_block):

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

    try:

        x = next(item for item in dict_list if item.get("Block") ==
search_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':
'21115674'},

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



    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__':

    main()





*Sample o/p:*



yy-1# python stack1.py

{'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()





Regards,

Ganesh



More information about the Python-list mailing list