<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def serialize(self, entity, request=None):
 """ Serialize entity into dictionary. The spec can affect how individual fields will be serialized by implementing ``serialize()`` for the fields needing customization. :returns: dictionary """


        def should_we_insert(value, field_spec):
            return value not in self.missing or field_spec.required

        errors = {}
        ret = {}

        for field_name, field_spec in self.spec.fields.items():
            value = self._get_value_for_serialization(entity, field_name, field_spec)
            func = self._get_serialize_func(field_name, self.spec)
            try:
                # perform serialization
                value = func(value, entity, request)
                if should_we_insert(value, field_spec):
                    ret[field_name] = value
            except ValidationError, e:
                if hasattr(e, 'message_dict'):
                    # prefix error keys with top level field name
                    errors.update(dict(zip(
                        [field_name + '.' + key for key in e.message_dict.keys()],
                        e.message_dict.values())))
                else:
                    errors[field_name] = e.messages

        if errors:
            raise ValidationError(errors)

        return None if ret == {} else ret