[Tutor] Input is Dictionary1, Output is Dictionary2 (using keys and values of Dictionary1)

Mats Wichmann mats at wichmann.us
Thu Jan 30 16:47:15 EST 2020


On 1/30/20 1:23 PM, Panchanathan Suresh wrote:
> Hi Everyone,
> 
> I spent a lot of time on this, trying out many things, but I am unable to
> create a new dictionary with the users as keys and a list of their groups
> as values.
> 
> Input Dictionary is {"local": ["admin", "userA"],"public":  ["admin",
> "userB"],"administrator": ["admin"] }
> Expected Output Dictionary is {"userA": ["admin","public"], "userB":
> ["admin"], "administrator": ["admin"]}
> 
> --- How to create an unique group for a particular user?
> --- And then how to add this user key and the user's value (which will be
> the list of groups the user belongs to)
> 
> *****
> def groups_per_user(group_dictionary):
>         user_groups = {}
>         groups = []
>         # Go through group_dictionary
>         for group,user in group_dictionary.items():
>                 # Now go through the users in the group
>                 for user1 in user:
>                         groups.append(group)
>                         print(user1,groups)
> 
>         return(user_groups)
> 
> print(groups_per_user({"local": ["admin", "userA"],"public":  ["admin",
> "userB"],"administrator": ["admin"] }))
> 
> *****

Hopefully this isn't a homework problem :)

You're not adding anything to your new dictionary. What you want to do
is use the user as a key, and a list of groups as the value; the trick
is that you may need to add several times to a user's entry, so you need
to handle both the case of "user not yet in dictionary" and the case of
"user has a grouplist, add to that list".  As a quick and dirty hack,
like this (I changed a name a bit for clarity):

    for group, userlist in group_dictionary.items():
        # Now go through the users in the group
        for user in userlist:
            try:
                user_groups[user].append(group)
            except KeyError:
                user_groups[user] = [group]



More information about the Tutor mailing list