0

The groups_per_user function receives a dictionary, which contains group names with the list of users. Users can belong to multiple groups. Fill in the blanks to return a dictionary with the users as keys and a list of their groups as values.

code

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

return(user_groups)

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

my code

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

  return(user_groups)

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

I am not able to figure out how to proceed further than this.

2
  • 1
    Please format your code properly, it seems the text in bold is part of your code Commented Jul 3, 2020 at 12:33
  • Your return statement is not at a valid indentation level. Commented Jul 3, 2020 at 12:37

3 Answers 3

1

Since you've not mentioned exactly what should be the required output. I believe you want unique values to act as keys and their respective key should be clubbed into one value.

For the same, below mentioned code is working.

def groups_per_user(group_dictionary):
    user_groups = {}
    for groups in group_dictionary:
      for user in group_dictionary[groups]:
          if user not in user_groups:
              user_groups[user] = [groups]
          else:
              user_groups[user].append(groups)   

    return(user_groups)


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

Output:

{'admin': ['local', 'public', 'administrator'], 'userA': ['local'], 'userB': ['public']}
Sign up to request clarification or add additional context in comments.

2 Comments

It certainly works, but is there any particular reason why you have renamed the variable group used in the question as groups? It only contains one group at a time.
Every time loop will iterate through one single group. It's a typo, I didn't notice that. group or groups works the same way.
1

You had made a good start (aside from some issues of formatting code in the question).

You need to append to a list that is a value in user_groups (with key user), first creating it as an empty list if it does not already exist.

def groups_per_user(group_dictionary):
    user_groups = {}
    for group in group_dictionary:
        for user in group_dictionary[group]:
            if user not in user_groups:
                user_groups[user] = []
            user_groups[user].append(group)

    return(user_groups)

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

In fact, you can use items() to give a sequence of 2-tuples containing (key, value) and unpack those into separate variables containing key and value (here group and users), avoiding the need for indexing using group_dictionary[group]:

def groups_per_user(group_dictionary):
    user_groups = {}
    for group, users in group_dictionary.items():  # <== use of items()
        for user in users:  # <== now we have the value (users) directly
            if user not in user_groups:
                user_groups[user] = []
            user_groups[user].append(group)
    return(user_groups)

Comments

1

There are already a couple of answers, but I find it worth mentioning that you could also use defaultdict to solve your problem. The usage is pretty straightforward - if the key is not found in the dictionary the defaultdict uses the method provided in the default_factory:

from collections import defaultdict 

def groups_per_user(group_dictionary):

    user_groups = defaultdict(list)

    for group in group_dictionary:
        for user in group_dictionary[group]:
            user_groups[user].append(group)

    return(user_groups)

print(
    groups_per_user({
        "local": ["admin","userA"],
        "public":["admin","userB"],
        "administrator": ["admin"]
    })
)
>>> defaultdict(<class 'list'>, {'admin': ['local', 'public', 'administrator'], 'userA': ['local'], 'userB': ['public']})

Constructing a defaultdict is more expensive than constructing a normal dict, but the performance is better.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.