不好意思,我不知道怎么解释。这里我要做的是对作为参数的字典进行迭代。然后返回一个新字典,它从键中获取列表值,并在包含该值的PREVIOUS字典中创建一个键列表。我一时想不明白。
谢谢你的帮助!
def groups_per_user(group_dictionary):
user_groups = {}
# Go through group_dictionary
for group, users in group_dictionary.items():
# Now go through the users in the group
for user in users:
# Now add the group to the the list of
# groups for this user, creating the entry
# in the dictionary if necessary
user_groups[user] = [group for user in group_dictionary]
return(user_groups)
print(groups_per_user({"local": ["admin", "userA"],
"public": ["admin", "userB"],
"administrator": ["admin"] }))
# Expected output: {'admin':['local','public','administrator'], 'userA':['local', 'userB':['public']}
如果您想要查看每个用户具有哪些组的权限/访问权限。添加到您提供的代码中,只需要添加几行额外的代码。
def groups_per_user(group_dictionary):
user_groups = {}
for group, users in group_dictionary.items():
for user in users:
if user in user_groups:
user_groups[user].append(group)
else:
user_groups[user] = [group]
return user_groups
groups_per_user(groups)
>> {'admin': ['local', 'public', 'administrator'],
'userA': ['local'],
'userB': ['public']}
一旦用户在当前循环中,检查他们是否在user_groups
中,如果是,则意味着列表已经存在,我们可以附加group
,否则我们将user
的键设置为当前group
的单个项目列表。