any suggestion on this code

MRAB python at mrabarnett.plus.com
Sun Apr 23 09:36:11 EDT 2017


On 2017-04-23 09:21, Ganesh Pal wrote:
> 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()
> 
If it's going to return a dict or something else, it's more usual for 
that "something else" to be None.

I think that the function is needlessly complicated and that this is better:


def return_matched_owner(dict_list,search_block):
      """Accepts a list of dictionary with owners and returns a dict if 
there is a match"""

     for item in dict_list:
         if item.get("Block") == search_block:
             return item

      return None


More information about the Python-list mailing list