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.
Answers
Answer:
While performing computations over dictionary, we can come across a problem in which we might have to perform the task of grouping keys according to value, i.e create a list of keys, it is value of. This can other in cases of organising data in case of machine learning. Let’s discuss certain way in which this task can be performed.
Method : Using sorted() + items() + defaultdict()
This task can be performed by combining the tasks which can be done by above functions. The defaultdict() is used to create a dictionary initialized with lists, items() gets the key-value pair and grouping is helped by sorted().
# Python3 code to demonstrate working of
# Grouping dictionary keys by value
# Using sorted() + items() + defaultdict()
from collections import defaultdict
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 1, 'for' : 3, 'CS' : 2}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Using sorted() + items() + defaultdict()
# Grouping dictionary keys by value
res = defaultdict(list)
for key, val in sorted(test_dict.items()):
res[val].append(key)
# printing result
print("Grouped dictionary is : " + str(dict(res)))
Output :
Answer:
>>>def groups_per_user(group_dictionary)
... user_group = { }
... for group, users in group_dictionary.items():
... for user in users:
... 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"] }))
output:
{'admin': ['local', 'public', 'administrator'], 'userA': ['local'], 'userB': ['public']}