mangelcs
mangelcs

Reputation: 3

Add new value to list as dictionary value in Python

The problem is: 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.

I tried to do the exercise but the computer doesn't recognize my answer as valid. I think it is because the brackets.

Here is my code:

def groups_per_user(group_dictionary):
   user_groups = {}
    for group, user in group_dictionary.items():
    
        for user in user:
            if user not in user_groups:
                user_groups[user] = group
            else:
                
                x = user_groups[user]
                new_group={}
                new_group = {user: [x,group]}
                
                user_groups.update(new_group)
                
    return(user_groups)
print(groups_per_user({"local": ["admin", "userA"],
        "public":  ["admin", "userB"],
        "administrator": ["admin"] }))

And I get

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

I tried to avoid the brackets too with this code instead


> new_group = {user: [x,group]}
> 
> new_group = {user: [str(x).lstrip('[').rstrip(']'),group]}

This time I get:

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

Both times were not valid.

Is there a better way?

Thank you all in advance for your help

Upvotes: 0

Views: 77

Answers (2)

Sheikh Mannan Sohail
Sheikh Mannan Sohail

Reputation: 11

You can use defaultdict to achieve this and avoid usage of the if-else condition

from  collections import defaultdict

def groups_per_user(group_dictionary):
    user_groups = defaultdict(list)
    for group, users in group_dictionary.items():

        for user in users:
            user_groups[user].append(group)
    return user_groups  # return dict(user_groups) if you want it to be returned in dict format


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

Upvotes: 0

rdas
rdas

Reputation: 21285

First of all

for user in user:

Will overwrite the iteration variable. Don't do this.

Second:

user_groups[user] = group

This will map the user to the group. Instead you can create the list of groups here directly with

user_groups[user] = [group] # single element list

Finally:

x = user_groups[user]
new_group={}
new_group = {user: [x,group]}
user_groups.update(new_group)

None of this is required. You can simply append the new group to the existing users list with:

user_groups[user].append(group)

Which gives us:

def groups_per_user(group_dictionary):
    user_groups = {}
    for group, users in group_dictionary.items():

        for user in users:
            if user not in user_groups:
                user_groups[user] = [group]
            else:
                user_groups[user].append(group)
    return user_groups


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

Ouput:

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

Upvotes: 6

Related Questions