[Tutor] Input is Dictionary1, Output is Dictionary2 (using keys and values of Dictionary1)
Mats Wichmann
mats at wichmann.us
Sat Feb 1 19:03:32 EST 2020
On 1/30/20 2:47 PM, Mats Wichmann wrote:
> 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]
Now some time has passed, I wanted to add, as a somewhat advanced topic
for those who may read this in the archives, that there are more concise
approaches. One way is to use, for the new calculated dictionary, a
derived class of dict, the defaultdict. With defaultdict, the behavior
of accessing a key that doesn't exist changes: instead of raising a
KeyError, the key is automatically inserted with an empty value of the
type specified when instantiating the defaultdict, and then things
proceed as normal. In this case we want a list, so we can rewrite the
above stuff like this:
from collections import defaultdict
def groups_per_user(group_dictionary):
user_groups = defaultdict(list)
# Go through group_dictionary
for group, userlist in group_dictionary.items():
# Now go through the users in the group
for user in userlist:
user_groups[user].append(group)
return user_groups
More information about the Tutor
mailing list