Advertisement
ElenaR1

queries-bogi.py

Apr 7th, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.29 KB | None | 0 0
  1. import csv
  2.  
  3. def filter(file_name, **kwargs):
  4.     list_of_dictionaries = []
  5.     result=[]
  6.     list_with_results = []
  7.     f = open(file_name, 'rt')
  8.     try:
  9.         reader = csv.DictReader(f)
  10.         for row in reader:
  11.             list_of_dictionaries.append(row)
  12.         add = True
  13.         #print(list_of_dictionaries)
  14.         for element in list_of_dictionaries:
  15.             for key, value in kwargs.items():
  16.                 if key in element:
  17.                     if element[key] == value:
  18.                         continue
  19.                     else:
  20.                         add = False
  21.                 elif key == 'full_name_startswith':
  22.                    
  23.                     if element['full_name'].split(' ')[0] == value:
  24.                         continue
  25.                     else:
  26.                         add = False
  27.                 elif key == 'email__contains':
  28.                     first, second = element['email'].split('@')
  29.                     value = value[1:]
  30.                     second = second[:len(second) - 4]
  31.                     if second == value:
  32.                         continue
  33.                     else:
  34.                         add = False
  35.                 elif key == 'salary_gt':
  36.                     if int(element['salary']) > value:
  37.                         continue
  38.                     else:
  39.                         add = False
  40.                 elif key == 'salary_lt':
  41.                     if int(element['salary']) < value:
  42.                         continue
  43.                     else:
  44.                         add = False
  45.                 else:
  46.                     pass
  47.             if add:
  48.                 result.append(element)
  49.             else:
  50.                 add = True
  51.         if 'order_by' in kwargs.keys():
  52.             print(kwargs['order_by'])
  53.             result = sorted(result, key=lambda k: k[kwargs['order_by']])
  54.  
  55.         for element in result:
  56.             elements = [val for val in element.values()]
  57.             list_with_results.append(elements)
  58.  
  59.         return list_with_results
  60.     finally:
  61.         f.close()
  62. #print(filter('example_data.csv',full_name="Diana Harris"))
  63. print(filter('example_data.csv',full_name__starswith="Michael",favourite_color="purple"))
  64. print(filter('example_data.csv',full_name__starswith="Michael",order_by='salary'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement