1

Sorry for the bad title wording, didn't know how to explain it. What I want to do here is itarate over the dictionary given as a parameter. I then return a new dictionary that grabs the list value from a key and creates a list of the keys in the PREVIOUS dictionary that contained the value. At the moment, I cannot figure it out.

Thank you for any help!

def groups_per_user(group_dictionary):
    user_groups = {}
    
    # Go through group_dictionary
    for group, users in group_dictionary.items():
        # Now go through the users in the group
        for user in users:
            # Now add the group to the the list of
            # groups for this user, creating the entry
            # in the dictionary if necessary
            user_groups[user] = [group for user in group_dictionary]

    return(user_groups)

print(groups_per_user({"local": ["admin", "userA"],
        "public":  ["admin", "userB"],
        "administrator": ["admin"] }))
# Expected output: {'admin':['local','public','administrator'], 'userA':['local', 'userB':['public']}

1 Answers1

2

IIUC you want to see which groups each user has permissions/access to. Adding to the code you provided only a few additional lines of code are needed.

def groups_per_user(group_dictionary):
    user_groups = {}
    for group, users in group_dictionary.items():
        for user in users:
            if user in user_groups:
                user_groups[user].append(group)
            else:
                user_groups[user] = [group]
    return user_groups

groups_per_user(groups)

>> {'admin': ['local', 'public', 'administrator'],
 'userA': ['local'],
 'userB': ['public']}

Once you have the user in your current loop, check to see if they are in user_groups, if yes that means the list already exists and we can append the group, otherwise we set the key of the user equal to a single item list with the current group.

gold_cy
  • 13,648
  • 3
  • 23
  • 45