首页 > 解决方案 > 如何在字典中修改?

问题描述

groups_per_user 函数接收一个字典,其中包含组名和用户列表。用户可以属于多个组。填空返回一个字典,其中用户作为键,他们的组列表作为值

def groups_per_user(group_dictionary):
    user_groups = {}
    # Go through group_dictionary
    for ___:
        # Now go through the users in the group
        for ___:
            # Now add the group to the list of
# groups for this user, creating the entry
# in the dictionary if necessary

    return(user_groups)

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

标签: pythondictionary

解决方案


def groups_per_user(group_dictionary):
    user_groups = {}
    # Go through group_dictionary
    for group in group_dictionary:
        # Now go through the users in the group
        for user in group_dictionary[group]:
            try:
                user_groups[user].append(group)
            except KeyError:
                user_groups[user] = [group]
            # Now add the group to the list of
# groups for this user, creating the entry
# in the dictionary if necessary

    return(user_groups)

推荐阅读