<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def bucket_policy_to_dict(policy):
 """Produce a dictionary of read, write permissions for an existing bucket policy document"""

    import json

    if not isinstance(policy, dict):
        policy = json.loads(policy)

    statements = {s['Sid']: s for s in policy['Statement']}

    d = {}

    for rw in ('Read', 'Write'):
        for prefix in TOP_LEVEL_DIRS:
            sid = rw.title() + prefix.title()

            if sid in statements:

                if isinstance(statements[sid]['Principal']['AWS'], list):

                    for principal in statements[sid]['Principal']['AWS']:
                        user_name = principal.split('/').pop()
                        d[(user_name, prefix)] = rw[0]
                else:
                    user_name = statements[sid]['Principal']['AWS'].split('/').pop()
                    d[(user_name, prefix)] = rw[0]

    return d