如何反转字典中键的值分配?求解算法

新手上路,请多包涵

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

基本上我正在尝试将组分配给用户而不是用户分配给组

这就是我到目前为止所尝试的:

 def groups_per_user(group_dictionary):
    user_groups = {}
    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 list of
          # groups for this user, creating the entry
          # in the dictionary if necessary
          groups.append(group)
          user_groups[user] = group

    return(user_groups)

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

如何遍历抛出列表,同时尽可能高效地将用户添加到组名中?

请原谅我的语法,这是我的第一个问题。谢谢

原文由 Abdu Samaraie 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 361
2 个回答

您的代码的问题是只有一个 groups 列表,而您真正想要的是每个用户的组列表。尝试这个

def groups_per_user(group_dictionary):
    user_groups = {}
    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

或者,我们可以用 setdefault 调用替换这三行:

 def groups_per_user(group_dictionary):
    user_groups = {}
    for group, users in group_dictionary.items():
        for user in users:
            user_groups.setdefault(user, []).append(group)
    return user_groups

第三种选择是使用 defaultdict:

 from collections import defaultdict

def groups_per_user(group_dictionary):
    user_groups = defaultdict(list)
    for group, users in group_dictionary.items():
        for user in users:
            user_groups[user].append(group)
    return user_groups

原文由 Dennis 发布,翻译遵循 CC BY-SA 4.0 许可协议

没关系伙计们我刚刚解决了它。我所需要的只是按用户获取组并将其连接到一个空列表中:

新代码是

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] = user_groups.get(user,[]) + [group]

    return(user_groups)

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

原文由 Abdu Samaraie 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题