<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_dict_to_policy(args, bucket_name, d):
 """ Create a bucket policy document from a permissions dict. The dictionary d maps (user, prefix) to 'R' or 'W'. :param bucket_name: :param d: :return: """


    import json

    iam = get_resource(args, 'iam')

    statements = make_bucket_policy_statements(bucket_name)

    user_stats = set()  # statement tripples

    for (user, prefix), mode in d.items():

        user_stats.add((user, 'list'))
        user_stats.add((user, 'bucket'))

        if mode == 'R':
            user_stats.add((user, 'Read' + prefix.title()))
            user_stats.add((user, 'List' + prefix.title()))
        elif mode == 'W':
            user_stats.add((user, 'List' + prefix.title()))
            user_stats.add((user, 'Read' + prefix.title()))
            user_stats.add((user, 'Write' + prefix.title()))

    users_arns = {}

    for user_name, section in user_stats:
        section = statements[section]

        if user_name not in users_arns:
            user = iam.User(user_name)
            users_arns[user.name] = user
        else:
            user = users_arns[user_name]

        section['Principal']['AWS'].append(user.arn)

    for sid in list(statements.keys()):
        if not statements[sid]['Principal']['AWS']:
            del statements[sid]

    return json.dumps(dict(Version="2012-10-17", Statement=list(statements.values())), indent=4)