1. import json
  2. def map_form_fields(form_data, field_mapping):
  3. """
  4. Maps fields from a form data dictionary to a desired structure
  5. based on a provided field mapping.
  6. Args:
  7. form_data (dict): A dictionary representing the form data.
  8. field_mapping (dict): A dictionary defining the mapping
  9. from form fields to target fields.
  10. Example: {'form_field_1': 'target_field_1',
  11. 'form_field_2': 'target_field_2'}
  12. Returns:
  13. dict: A dictionary containing the mapped fields.
  14. Returns an empty dictionary if form_data is empty.
  15. """
  16. if not form_data:
  17. return {}
  18. mapped_data = {}
  19. for form_field, target_field in field_mapping.items():
  20. if form_field in form_data:
  21. mapped_data[target_field] = form_data[form_field]
  22. return mapped_data
  23. if __name__ == '__main__':
  24. # Example usage
  25. form_data = {
  26. 'first_name': 'John',
  27. 'last_name': 'Doe',
  28. 'email': 'john.doe@example.com',
  29. 'phone_number': '123-456-7890'
  30. }
  31. field_mapping = {
  32. 'first_name': 'name',
  33. 'last_name': 'surname',
  34. 'email': 'email_address'
  35. }
  36. mapped_data = map_form_fields(form_data, field_mapping)
  37. print(json.dumps(mapped_data, indent=4))
  38. #Example with empty form data
  39. empty_form_data = {}
  40. mapped_data = map_form_fields(empty_form_data, field_mapping)
  41. print(json.dumps(mapped_data, indent=4))

Add your comment