I don't understand what I'm doing wrong

My Task:

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.

My answer:

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


    return(user_groups)

print(groups_per_user({"local": ["admin", "userA"],
        "public":  ["admin", "userB"],
        "administrator": ["admin"] }))
Error on line 17:
    "administrator": ["admin"] }))Error on line 8:
    user_groups[users].append(groups)
AttributeError: 'str' object has no attribute 'append'

>Solution :

Line user_groups[users] = groups to user_groups[users] = [groups]

# this line is creating issue because if users is not in dictionary then you are initialising that key with a string and if key is found then the value will be string and string will not support append operation thatswhy you are getting an error

Just edit this

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


    return(user_groups)

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

Leave a Reply