<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def apply_policy(self, sp_entity_id, policy, metadata=None):
 """ Apply policy to the assertion I'm representing :param sp_entity_id: The SP entity ID :param policy: The policy :param metadata: Metadata to use :return: The resulting AVA after the policy is applied """


        policy.acs = self.acs
        ava = policy.restrict(self, sp_entity_id, metadata)

        for key, val in list(self.items()):
            if key in ava:
                self[key] = ava[key]
            else:
                del self[key]

        return ava